I want remove the users from Azure subscriptions programmatically.
We have lot of ways in the web to remove the AAD user but I could not find source to remove the users from Azure subscriptions.
Can we remove the user from Azure subscriptions programmatically?
How can we do this?
Have you tried working with the Azure API Reference? Specifically authorization?
You may be interested in the Role Assignments API.
Here's a support article regarding those assignments and how to utilize the API: https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-rest
Finally i found the answer. We have to do multiple steps to remove the user from Subscription.
Before we start implementing the below steps you need to create Client Id and client secret and create auth token using those client id and secret.
First i am fetching all the users by below GET API. Here is URL for reference.
example get method URL for above reference is: https://management.azure.com/subscriptions/{your subscription id here}/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01
Above URL will fetch all the Users principal Id(User GUID) and RoleAssigementID.
Then you can delete a specific user you want. Same above URL has reference to remove the User from Susbcription.
example delete method URL for above reference is: https://management.azure.com//subscriptions/{your subscription id here}/providers/Microsoft.Authorization/roleAssignments/{User role Assignment id}/providers/Microsoft.Authorization/roleAssignments/{User role Assignment id}?api-version=2015-07-01
You can find the role assignment id from the first step.
Extra information:
First step will fetch principal id and role id but if you need other information of the user(ex: emailid, name, etc) you can use Graph API to fetch all information of the User. Here is the URL for reference.
Before calling this API, you need to create another auth token(which is different from above auth token) for this.
https://graph.windows.net/{your tenant id}/getObjectsByObjectIds?api-version=1.6
Related
I have a
back-end application - ASP.NET Web API
front end - React.
We are using a third party for authentication and have role based access for authorization.
We found an issue where in user who is authenticated and authorized was able to change an id say documentid in GET call (/API/Document/{documentid}) and was able to view other user data.
So after researching one way is to check on the call if the owner of the document (userid) matches the userid of the logged in. Since its Web API we cannot store the userid in session, so we had to set the userid in JWT. So when logged in we set the userid in JWT and we can make a check on the calls to see if the owner of the resource matches with userid in JWT. I see some concerns adding/exposing userid in JWT, so the question is what is the best way to handle it? I can make use of username but that might add an overhead of database call to get userid or add the username in every view model.
I am using identity server 4 for authentication and authorization, and user permissions are saved in JWT and then used on API-s to check if users has required permission.
But the problem is that JWT got too big and I would like to remove permissions from it, and make custom authorization on API-s so that its fetches permissions from identity server instead of getting it from JWT.
API would get only userId from JWT and then based on that fetch additional information from identity server. Is it possible to do something like that?
We basically have a similar problem in our application.
The way to solve this problem is using an event which is raised at the level of the API resource (the API which you are protecting by using JWT bearer tokens authentication) once the JWT token has been read from the incoming request and validated.
This event is called OnTokenValidated, see here for more details.
This is the top level plan:
keep your JWT bearer token minimal. At the very minimum it contains the subject id, which is the unique identifier of the user at the identity provider level. You can put other claims there, but the idea is that the JWT bearer token must be small
implement a way to get the user permissions given the user unique identifier (you can use the subject id as an identifier or any other id which makes sense in your system)
make the user permissions fetch mechanism of the previous point accessible via api call. Caching this API is a good idea, because usually permissions are stable. Defining a smart way to evict this cache is beyond the scope of this answer, but it's something you should definitely think about.
once you have fetched the user permissions (via an API call) you need to make them available to the ASP.NET core authorization framework. The simplest way to do so is create a custom claim type (for instance: "app_permission") and create one user claim per each user permission. Each of these permission claims has the custom claim type ("app_permission") and the permission name as the claim value. For instance a user having the two permissions "read-content" and "write-content" will have two claims both having "app_permission" as the claim type, the first one having "read-content" as the claim value and the second one having "write-content" as the claim value.
the permissions claims defined at the previous point can be injected in the user identity (at the API resource level) by defining an additional ClaimsIdentity for the user and by adding it to the current user identity. The process depicted here is quite similar to a claims transformation done by an MVC application using cookie authentication.
In the Startup class of your API resource, in the point where you register the authentication services, you can do something like this:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:8080";
options.Audience = "sample-api";
options.RequireHttpsMetadata = false;
// register callbacks for events
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
if (!context.Principal.Identity.IsAuthenticated)
{
return;
}
var subjectId = context.Principal.FindFirst(JwtClaimTypes.Subject)?.Value;
if (string.IsNullOrWhiteSpace(subjectId))
{
return;
}
// do whatever you want with the user subjectId in order to get user permissions.
//You can resolve services by using context.HttpContext.RequestServices which is an instance of IServiceProvider
//Usually you will perform an API call to fetch user permissions by using the subject id as the user unique identifier
// User permissions are usually transformed in additional user claims, so that they are accessible from ASP.NET core authorization handlers
var identity = new ClaimsIdentity(userPermissionsClaims);
context.Principal.AddIdentity(identity);
}
};
});
+1 for the accepted answer but I would just like to offer an alternative solution to this problem. If your permissions are pretty simple like readResource or writeResource then you could define all your permissions as enum and use integers instead of strings in JWT, that would reduce JWT size.
If permission list is still huge then you could also group permissions together so that the permission list is smaller for some customers e.g. merge readResource, writeResource, updateResource, deleteResource into one permission called crudResource.
How do I create a user using Microsoft graph? For I am having issues with regards to permission failures during a save.
I do have few questions in mind.
Where will the user be created by calling create user API in graph ? Is it in Azure AD or somewhere else ?
I tried calling create user api by passing json and required headers, below is the error I get
Where exactly do I need to set the permission, I have already added permissions in the Application Registration Portal
But when API is executed it shows that I don't have enough permission.
FYI, I have registered the app using the same email id that I am using to test the APIs here https://developer.microsoft.com/en-us/graph/graph-explorer#
If I am not the admin, where exactly do I need to set or request for it ?
In order to create a User via Microsoft Graph, you need to request either Directory.ReadWrite.All or Directory.AccessAsUser.All permission.
Important: Directory.ReadWrite.All and Directory.AccessAsUser.All both require Admin Consent before you can use them. If you're using Graph Explorer then the URI you need to provide your tenant Admin will be generated for you. If you're doing this in your own application, you'll need to construct an Admin Consent URI yourself. You can find more details on this at v2 Endpoint & Admin Consent.
Once you have the proper permissions configured (and consented), you'll want to POST the following JSON body/payload to https://graph.microsoft.com/v1.0/users:
{
"accountEnabled": true,
"displayName": "displayName-value",
"mailNickname": "mailNickname-value",
"userPrincipalName": "upn-value#tenant-name.onmicrosoft.com",
"passwordProfile" : {
"forceChangePasswordNextSignIn": true,
"password": "password-value"
}
}
This will create a user with a temporary password. The user will be asked to set a new password as after as they authenticate for the first time.
Where will the user be created by calling create user API in graph ?
Is it in Azure AD or somewhere else ?
Yes, the user created is in the Azure AD.
I tried calling create user api by passing json and required headers,
below is the error I get
For your error, have you added the request body like the following, and this required admin:
Where exactly do I need to set the permission, I have already added
permissions in the Application Registration Portal
The required permissions to create application:
For the details, please read here.
I created an ASP.NET MVC Core (1.1.0) application using VS2015. In the dialog, I selected the option to connect to Azure AD, so VS generated the boilerplate code and, as expected, the app redirects me to Microsoft's login page, where I can login with my work&school account.
Now, after the user logs in, and before serving the first page (say, /home/index) I need to get some information from the user that I have stored in a database (like the display name, the contact information such as an email, phone number, address, a picture of the user, and so on).
What I have thought so far is to add a ControllerBase with a method that retrieves this info, and then pass it to the views via ViewData. But querying the database for this info over and over seems inefficient. An alternative would be to store this info in a cookie or in a session state, thus only hitting the database once. But having to depend on a ControllerBase could lead to errors (for instance, if in some controller method one forgets to call the base's method) and doesn't feel like they way to go. Also, having this funcionality on the home controller only could fail if a user enters the URL with a predefined path (as in www.myapp.com/Users/joedoe/Detail).
I searched and found a reference to using the Events property in the OpenIdConnectOptions object passed to the application builder in the Startup class:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["Authentication:AzureAd:ClientId"],
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
Events = new OpenIdConnectEvents {
//
}
});
However, the OpenIdConnectEvents class does not have some "OnAuthenticationSucceeded" event, it only has an OnAuthenticationFailed, which is not what I want, and other callbacks whose names doesn't seem to be what I'm looking for.
So, my question, what is the callback I should be using with OpenIdConnectEvents, or, alternatively, what's the preferred way for ASP.NET MVC Core applications that connect to AAD to catch an event after the user has been authenticated?
Thanks in advance.
There is an assortment of various OpenIdConnectEvents you can hook into. Look at SecurityTokenValidated. This fires after the user has authenticated to AAD and the token had been validated. Here you can look up data in a database and add your own claims to the identity (like roles, etc).
This sample goes and resolves group names from AAD, but the concept is the same - add additional data to the claim set and you can access it through the user principal throughout the application. Using a ClaimType of role will let you use the existing attributes in ASP.net (like the Authorize(Role=...) attribute.
https://github.com/jpda/azure-ad-netcore-sample/blob/master/src/azure-ad-netcore-sample/Startup.cs
I have created a new application in Azure AD using the AAD Graph API. (code)
Unfortunately it doesn't let my client access the requested resources until I have been to the application's configuration page in the Azure management portal and made a cosmetic change, and then saved it. After removing the change and saving again, it still works.
The application manifest files before the change + change back steps and after them are completely identical (as in diff.exe says they are the same).
When comparing the JWT tokens returned when the application authenticates, it shows that the post-change access token includes the "roles" section. The entire "roles" section is not present in the access token returned before saving the application in the management portal.
So it seems the Azure management portal does "something" to the application when saving changes. The question is what it is, and can I do the same using the AAD graph API?
There were several issues. Some bugs in the backend on Azure, which have now been fixed, and also some missing calls to the API which I didn't know were necessary.
Thanks to some very helpful people at MS Support, we were able to get it to work.
When creating an application, you need to do the following:
Create an application object.
Setup the RequiredResourceAccess for the application, ie. which permissions the appliation has to Azure Graph API etc. This is what is configured in the portal's "permissions to other applications" settings. You can get the necessary GUIDs by configuring the permissions manually, and then looking in the application's AAD manifest file.
Create a service principal for the application.
Add AppRoleAssignments to the service principal.
The final part is what I was missing before. Even though you have configured RequiredResourceAccess on the application object, the service principal still needs the AppRoleAssignments to actually have permission to access the resources.
When creating the AppRoleAssignments it is a little bit tricky to figure out which PrincipalId to assign, since that is the AAD ObjectId of the service principal for the other resource.
Here is a snippet for adding the AppRoleAssignment to access the Azure AD Graph API. client is an ActiveDirectoryClient instance, and sp is the ServicePrincipal for my application:
// find the azure ad service principal
var aadsp =
client.ServicePrincipals.Where(csp => csp.AppId == "00000002-0000-0000-c000-000000000000")
.ExecuteSingleAsync().Result;
// create the app role assignment
var azureDirectoryReadAssignment = new AppRoleAssignment
{
PrincipalType = "ServicePrincipal",
PrincipalId = Guid.Parse(sp.ObjectId), //
Id = Guid.Parse("5778995a-e1bf-45b8-affa-663a9f3f4d04"), // id for Directory.Read
// azure active directory resource ID
ResourceId = Guid.Parse(aadsp.ObjectId) // azure active directory resource ID
};
// add it to the service principal
sp.AppRoleAssignments.Add(azureDirectoryReadAssignment);
// update the service principal in AAD
await sp.UpdateAsync();
My experience is that you need to wait a short time, maybe 2-3 minutes, before the newly created objects are valid in AAD, and then you can authenticate using the new application.
Apart from RasmusW's answer above, there a few more things that you might have to do depending on what you are trying to achieve.
If you want delegated permissions to work, you also need to add an Oauth2PermissionGrant into Oauth2PermissionGrants collection at the root level. This should have clientId of caller's SPN ObjectId, ResourceId of called SPN's object Id. The Scope value of the Oauth2PermissionGrant is key. It should have space separated values. Each value here comes from the 'Value' property of the Oauth2Permission object on the target SPN.
Additionally you may also need to be in appropriate DirectoryRole e.g. Directory Readers.