How do I get the "Assigned Role" of a User in Azure Active Directory? - azure-active-directory

I am using Azure AD with a registered Application and I am using the Microsoft Graph API to query the AD.
The following code below tells which groups the User is Assigned to
var memberof = await graphClient.Users[xxx].MemberOf.Request().GetAsync();
I am using standard AD package and it seems that groups are somewhat restricted and I need to buy the "Premium AD Package" to use them fully.
So I don't want to use the group information. I am interested in the roles that I assign my users that I have put into my application manifest.
e.g
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"displayName": "Case Manager",
"id": "{A_Guid}",
"isEnabled": true,
"description": "Case Manager's can create and assign Cases to other users",
"value": "CaseManager"
},
So, how can I use the Graph Api to tell me if a user has a particular role ?

1. Microsoft Graph API
The ability to read all application specific roles assigned to a user (i.e. AppRoleAssignments) is only available as part of Microsoft Graph API beta endpoint currently AFAIK. This is not available as part of v1.0. You can read about versions here
As evident from name "beta", it's not expected to be a stable version that can be relied upon for production applications. Read more specific points in this SO Post by Marc LaFleur
Exact API (Microsoft Docs Reference):
GET https://graph.microsoft.com/beta/users/{id | userPrincipalName}/appRoleAssignments
I tried using GraphServiceClient (.NET SDK for Microsoft Graph) but wasn't able to find anything related to AppRoleAssignments. (probably because SDK uses metadata from stable 1.0 version and not the beta version)
In any case, if you can still test this, use Microsoft Graph Explorer or directly call the endpoint from C# code
string graphRequest = $"https://graph.microsoft.com/beta/users/{my user GUID}/appRoleAssignments";
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
2. Windows Azure AD Graph API
Even though it's recommended to use Microsoft Graph API whenever possible, there are still some cases where Microsoft Graph hasn't caught up yet so you are forced to use Azure AD Graph API. Application management related cases are some of those.
So you could use this Azure AD Graph API. I quickly tested this from Azure AD Graph Explorer and it works fine.
https://graph.windows.net/{yourtenantid}/users/{id}/appRoleAssignments?api-version=1.6
Just like Microsoft Graph Library for .NET you can use Azure AD Graph Client Library for .NET and your code would look something like this..
aadgraphClient.Users["<user guid>"].AppRoleAssignments;
On a side note, since you've asked the question specifically for Microsoft Graph API, I've answered it accordingly.
At least for the currently signed in user for an application, you can always find the Application Roles assigned to them from the Role claims available as part of the access token from Azure Active Directory.
This although only helps with roles for current user and not in management sort of scenarios if you're trying to go across all users for an application. Here's a sample that reads role claims and does authorization based on App Roles for currently signed in user.
Authorization in a web app using Azure AD application roles & role claims

I just found a way to get roles of an user at an application level.
You can create application level roles by updating the manifest's appRoles array.
[azure/app registrations/<your-app>/manifest)]
I used Microsoft.Graph.Beta, to get access to service principals api.
var userRoles = await _client.Me.AppRoleAssignments.Request().GetAsync();
The above query would fetch all the application roles for the user.
var appRoleAssignments = await _Client.ServicePrincipals[<<application_objectId>>].Request().GetAsync();
The above query would fetch all the roles of an application assigned at manifest level.
And application object Id could be found at [azure/app registrations/<your-app>)] -> Object ID
And execute the below to get list of user roles
var roles = new List<string>();
if (appRoleAssignments != null && appRoleAssignments.AppRoles.Any())
{
var userRolesOfCurrentResource = userRoles.First(role => role.ResourceId == Guid.Parse(<<application object id>>));
if(userRolesOfCurrentResource!=null)
{
var role = appRoleAssignments.AppRoles.First(role => role.Id == userRolesOfCurrentResource.AppRoleId);
if (role!=null)
{
roles.Add(role.Value);
}
}
}

Related

Microsoft graph - much of the user data returned from azure active directory is NULL

I am querying Azure Active Directory for users using Microsoft Graph API in .NET.
When i browse Active Directory in the azure portal, i can see the users have details such as user principal name.
When i query via .net however, the UPN is null (see image below)
This particular request was a delta query and the user is a new user.
The App Registration has the following Graph API permissions:
Any idea why the UPN is blank?
Code to get the delta:
lastDeltaPage.InitializeNextPageRequest(graphClient, deltaLink.ToString());
usersPage = await lastDeltaPage.NextPageRequest.GetAsync();
users.AddRange(usersPage.CurrentPage);
while (usersPage.NextPageRequest != null)
{
usersPage = await usersPage.NextPageRequest.GetAsync();
users.AddRange(usersPage.CurrentPage);
}
if(usersPage.NextPageRequest == null)
{
usersPage.AdditionalData.TryGetValue("#odata.deltaLink", out deltaLink);
}
return users;
Along with that please check the below points if they can help:
Sometimes when permission to read a certain type, members of that
type are returned but with limited information. For the object types
which the application does not have permission to read only the the
object type and ID are returned.
Please see Use delta query to track changes in Microsoft Graph data - Microsoft Graph | Microsoft Docs
Also there might not be any changes or updates to the user , or the properties are set to null so
changes may return null
Also check Delta Query Using the Microsoft Graph SDK 1.4 NuGet - Stack Overflow
References:
limited-information-returned-for-inaccessible-member-objects
user: delta - Microsoft Graph v1.0 | Microsoft Docs
Delta Queries In Microsoft Graph API Using C# – TekExpo
(wordpress.com)

How to add custom attributes for Azure AD B2B user

How can be added custom attribute for user in Azure AD B2B using API?
A found a way for External Identities but I'm looking for custom attributes regardless of user type.
For example, I want to have the attribute "FavoriteColor" for every user (member or guest)
How can I achieve that?
You can use Microsoft Graph API Create extensionProperty.
Specify the targetObjects as "User".
An example (you can use any of your app registrations for {object id of the app registration}):
Post https://graph.microsoft.com/v1.0/applications/{object id of the app registration}/extensionProperties
{"name":"customAttribute","dataType":"string","targetObjects":["User"]}
It will generate an extension property named extension_{client id of the app registration without "-"}_customAttribute.
Then you can update the extension property for the member or guest user:
Patch https://graph.microsoft.com/v1.0/users/{user id}
{"extension_{client id of the Azure AD application without "-"}_customAttribute":"value"}
Use Microsoft Graph Explorer to have a quick test.
Microsoft Graph auth overview and Microsoft Graph SDK for your reference.

Remove a user or group assignment to an enterprise app using Microsoft Graph

I would like to remove a user or group assignment to an enterprise app using Azure AD Graph or Microsoft Graph in C#.
Thanks,
Kevin
The answer provided by juunas is right, I just make some additions.
As you want to do this operation by c# code, so you can refer to my steps below:
1. Install two SDKs in your project.
Install-Package Microsoft.Graph.Auth -IncludePrerelease
Install-Package Microsoft.Graph.Beta -Version 0.14.0-preview
I referred to the document about install SDKs, but I can't find AppRoleAssignments in GraphServiceClient class. So please install SDKs with the commands above.
2. Please refer to the code below:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Security;
namespace ConsoleApp13
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
Console.WriteLine("Hello World!");
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("your client id")
.WithTenantId("your tenantid")
.Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, new string[] { "https://graph.microsoft.com/.default" });
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var securePassword = new SecureString();
string password = "your password";
foreach (char c in password)
securePassword.AppendChar(c);
await graphClient.Users["user object id"].AppRoleAssignments["role assignment id"].Request().WithUsernamePassword("email account", securePassword).DeleteAsync();
Console.WriteLine("----complete---");
}
}
}
The role assignment id in AppRoleAssignments["role assignment id"] above comes from the list query graph api: GET https://graph.microsoft.com/beta/servicePrincipals/{id}/appRoleAssignedTo/{id}
3. Before running the c# code, we need to enable we have assign the delegated permission Directory.AccessAsUser.All to the app and enable the button shown as below screenshot.
4. After that, we can running the code and remove the user or group successfully.
5. By the way:
(1) The code I provided is for remove users assignment. If you want to remove group assignment, just modify the code as:
await graphClient.Groups["group object id"].AppRoleAssignments["role assignment id"].Request().WithUsernamePassword("email account", securePassword).DeleteAsync();
(2) You need to pay attention to the beta version of api as juunas mentioned.
Hope it helps~
To do that, you'd need to call this endpoint in MS Graph API: https://learn.microsoft.com/en-us/graph/api/approleassignment-delete?view=graph-rest-beta&tabs=http.
Though the docs seem to be missing it, you should be able to list the assignments for a user etc. by doing a GET without an assignment id.
I don't think you can guess the assignment ids, so you'll need to read them first from there.
And though it says you need delegated permissions to call the endpoint, that isn't completely true.
You can give an app the access as user permission and then login with a user and act on their behalf.
But you can also have an app do these without a user.
You can assign an administrator role to the service principal running a script, and that will allow it to do this as well.
You can do this through the Roles and administrators tab in the AAD management UI.
The only tough situation here is that this ability is only in the beta version of MS Graph API.
But Azure AD Graph API is not recommended for use.
So, you have two options right now:
Use the beta version of MS Graph API for this, and upgrade as soon as the API reaches a stable version
beta is a bit volatile, so there some risks in using it in production
Use Azure AD Graph API and upgrade to MS Graph API once it reaches a stable version
this upgrade would probably be mandatory

How to update Secret Token property in Azure AD Synchronization API?

I am trying to find a way how to programmatically change properties of Enterprise Application (non-catalogue app), specifically Secret Token and Tenant ULR in 'Provisioning' blade, allowing to synchronize user/group objects between AAD and an external app (e.g. SaaS app) that supports it.
My customer has a strict policy to rotate all secrets and keys in Azure in regular intervals, so they want to be able to have an automation runbook that would change that token in the app (it is actually an Azure Databricks instance that supports this sync) as well as in AAD.
I checked whether there was a direct PowerShell support but I couldn’t find a specific cmdlet for this scenario (tried both GA and preview versions of AAD PowerShell 2.0).
I found a good documentation page describing AAD Synchronization API - https://learn.microsoft.com/en-us/graph/api/resources/synchronization-overview?view=graph-rest-beta – however, I am unable to find, how to update the Secret Token property.
Ideally, I would like to see a code sample of a REST call on how change that specific property using Synchronization API. A PowerShell example would be even better. Any help is much appreciated. Thanks.
Here's how to do it for non-gallery SCIM apps:
PUT https://graph.microsoft.com/beta/servicePrincipals/99abefe8-3ad8-488f-b14f-df209cbc1ab3/synchronization/secrets
{
value: [
{ key: "BaseAddress", value: "xxxxxxxxxxxxxxxxxxxxx" },
{ key: "SecretToken", value: "xxxxxxxxxxxxxxxxxxxxx" }
]
}
Replace the GUID after servicePrincipals with your real servicePrincipal object ID.
For apps that aren't non-gallery SCIM apps, the credential names required can be discovered in the metadata -> configurationFields part of the synchronizationTemplate object:
https://learn.microsoft.com/en-us/graph/api/resources/synchronization-synchronizationtemplate?view=graph-rest-beta

Unable to get user company information on microsoft graph API

I'm having a problem with Microsoft Graph API... Currently I have a web application that has an openid integration with Microsoft/Azure using the common v2 endpoint.
We are trying to get the signed in user company name and job information. The official docs say that we need to make a request to the MS Graph API.
We are testing it on Microft Graph Explorer but it doesn't seem to work.
We've selected the 'User.Read' as a permission in our app, then tried these endpoints:
https://graph.microsoft.com/v1.0/me/
https://graph.microsoft.com/v1.0/me?$select=companyName,jobTitle
https://graph.microsoft.com/v1.0/users/?$select=companyName,jobTitle
In MS offical doc (https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference) on User/Remarks sections, it clearly says that
"On reads, only a limited number of properties are returned by default. To read properties that are not in the default set, use $select"
Is this doc outdated?
I've tried to reach MS support for developers, but they answered saying that I should ask this on Stack Overflow...
So probably there are no official support for developers?
Is it really possible to get the company name and job title from a MS account?
Thanks in advance!
edit. Update question with MS graph explorer screenshots
edit.2. Update screenshot with proper encoding.
Also, it's a MS account not an Azure account, since our web app accepts both of them on the common v2 endpoint.
Update
My goal was trying to get the Work Info section from a MSA account.
The documentation is correct, by default we only return a subset of user properties:
id
userPrincipalName
displayName
givenName
surname
jobTitle
mail
mobilePhone
businessPhones
officeLocation
preferredLanguage
If you want a different set of properties, you can request them using the $select query parameter. The queries you provided in your question should work fine. For example, when I execute https://graph.microsoft.com/v1.0/me?$select=companyName in Graph Explorer (after logging in with my credentials) I get the following:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(companyName)/$entity",
"companyName": "MICROSOFT"
}
Update Regarding MSA
When using Microsoft Graph against a Microsoft Account (MSA) there are several differences in what properties get surfaced. As an MSA is by definition a personal/individual account, organizational properties such as Job Title and Office Location are simply not applicable.

Resources