How to get user group information from Azure AD B2C - azure-active-directory

I am using Microsoft Graph for fetching user information, namely "List users" API.
Following is the code for accessing the user information :
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, clientCred);
string token = authenticationResult.AccessToken;
Debug.WriteLine("token=" + token);
var responseString = String.Empty;
string[] scopes = { "User.Read" };
using (var client = new HttpClient())
{
string requestUrl = "https://graph.microsoft.com/v1.0/users?$select=id,givenName,surname";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
Debug.WriteLine(request.ToString());
HttpResponseMessage response = client.SendAsync(request).Result;
responseString = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine(responseString);
}
Output :
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(id,givenName,surname)",
"value": [
{
"id": "000000000-0000-0000-000-000000000",
"givenName": "XXX",
"surname": "XXX"
}, {
"id": "000000000-0000-0000-000-000000000",
"givenName": "XXX",
"surname": "XXX"
}
]
}
How to the get user group ?

You can call the user: getMemberGroups API action for a user to get their groups:
You need to make a request like so:
POST https://graph.microsoft.com/v1.0/users/user-id-here/getMemberGroups
Content-type: application/json
Content-length: 33
{
"securityEnabledOnly": true
}
The securityEnabledOnly parameter defines if it should only return security groups. Setting it to false will also return the user's Office 365 group memberships for example.
An alternative is to use the memberOf navigation property:
GET https://graph.microsoft.com/v1.0/users/user-id-here/memberOf
This returns the groups and directory roles the user is a direct member of.

Related

Added Custom Claim, showing in ID token missing in Access token

I have a .NET Core Identity Provider (which also uses IdentityServer4) which authenticates SPA applications with Azure AD. I am adding an "oid" claim with the object identifier value received from Azure. The problem is that from the SPA application I can see the "oid" claim in the ID token but cannot see it in the access token. I need the oid in the access token as well. Here is the relevant code:
Startup.cs
services.AddAuthentication()
.AddCookie("Cookies", options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
})
.AddOpenIdConnect(ActiveDirectoryTenants.TenantA, ActiveDirectoryTenants.TenantA, options => Configuration.Bind("TenantAAzureAd", options))
.AddOpenIdConnect(ActiveDirectoryTenants.TenantB, ActiveDirectoryTenants.TenantB, options => Configuration.Bind("TenantBAzureAd", options));
AddActiveDirectoryOpenIdConnectOptions(services, ActiveDirectoryTenants.TenantA);
AddActiveDirectoryOpenIdConnectOptions(services, ActiveDirectoryTenants.TenantB);
I have a common function to add other options to these configurations. I tried to add the oid claim in OnTokenValidated but didn't receive the oid claim in the access token.
protected virtual void AddActiveDirectoryOpenIdConnectOptions(IServiceCollection services, string tenant)
{
services.Configure<OpenIdConnectOptions>(tenant, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.ValidateIssuer = false;
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = ctx =>
{
ctx.ProtocolMessage.LoginHint = ctx.Properties.GetString("username");
return Task.CompletedTask;
},
OnTokenValidated = ctx =>
{
//Maybe need to add oid here???
}
};
});
}
The oid claim is being added after successfully logging in to Azure AD.
AccountController.cs
public async Task<IActionResult> ExternalLoginCallback(string returnUrl, string remoteError = null, string openIdScheme = null)
{
var authResult = await HttpContext.AuthenticateAsync(openIdScheme ?? ActiveDirectoryTenants.TenantA);
var externalUser = authResult.Principal;
var claims = externalUser.Claims.ToList();
var applicationUser = //gets the user based on the email found in claims, omitted for brevity
await userManager.AddClaimAsync(applicationUser, new Claim("oid", claims.First(x => x.Type == http://schemas.microsoft.com/identity/claims/objectidentifier).Value));
await signInManager.SignInAsync(applicationUser, false, "AzureAD");
return Redirect("~/");
}
The ID token received in the SPA application (note the oid claim):
{
"nbf": xxx,
"exp": xxx,
"iss": "https://localhost:3000",
"aud": "xxx-spa-test",
"iat": xxx,
"at_hash": "",
"s_hash": "",
"sid": "",
"sub": "guid",
"auth_time": 1620026953,
"idp": "AzureAD",
"display_name": "Test User",
"oid": "guid",
"role": [
"Staff",
],
"name": "test#azureaddomain",
"amr": [
"external"
]
}
The access token received in the SPA application (note the missing oid claim):
{
"nbf": xxx,
"exp": xxx,
"iss": "https://localhost:3000",
"aud": [
"https://localhost:3000/resources",
"xxx-api-test-scope"
],
"client_id": "xxx-spa-test",
"sub": "guid",
"auth_time": 1620026953,
"idp": "AzureAD",
"role": [
"Staff",
],
"name": "test#azureaddomain",
"scope": [
"openid",
"profile",
"xxx-api-test-scope"
],
"amr": [
"external"
]
}
For the claim to end up in the access token, you need to add a ApiScope and add the Userclaim name to it. Alternatively, add an ApiScope and an ApiResource that contains the UserClaim.
Like
var apiresource1 = new ApiResource()
{
Name = "apiresource1", //This is the name of the API
ApiSecrets = new List<Secret>
{
new Secret("myapisecret".Sha256())
},
Description = "This is the order Api-resource description",
Enabled = true,
DisplayName = "Orders API Service",
Scopes = new List<string> { "apiscope1"},
UserClaims = new List<string>
{
//Custom user claims that should be provided when requesting access to this API.
//These claims will be added to the access token, not the ID-token!
"apiresource1-userclaim3",
}
};
See my answer here for more details
To complement this answer, I write a blog post that goes into more detail about this topic:
IdentityServer – IdentityResource vs. ApiResource vs. ApiScope

Can not create a team from scratch via microsoft graph api

I follow this document and tried to create a team in the code
https://learn.microsoft.com/en-us/graph/api/team-post?view=graph-rest-1.0&tabs=csharp%2Chttp.
here is my code snippets:
var scopes = new string[] { "https://graph.microsoft.com/.default" };
// Configure the MSAL client as a confidential client
var confidentialClient = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);
// Make a Microsoft Graph API call
var team = new Team
{
DisplayName = "My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
{"members#odata.bind", "[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-1111-b41e-22229f05911c\"}]"}
}
};
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);
// Make a Microsoft Graph API call
var team = new Team
{
DisplayName = "My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
{"members#odata.bind", "[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-4105-b41e-1ba89f05911c\"}]"}
}
};
but get this error:
"message": "Bind requests not supported for containment navigation property.",\r\n
I'm using the latest Microsoft.Graph library and version is V3.1.8
does anyone have some ideas on this issue or the odata format error?
It seems that the members#odata.bind is still in change. It doesn't work currently.
You need to use members property.
POST https://graph.microsoft.com/v1.0/teams
{
"template#odata.bind":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
"displayName":"My Sample Team555",
"description":"My Sample Team’s Description555",
"members":[
{
"#odata.type":"#microsoft.graph.aadUserConversationMember",
"roles":[
"owner"
],
"userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
]
}
The corresponding C# code should be:
var team = new Team
{
DisplayName = "My Sample Team557",
Description = "My Sample Team’s Description557",
Members = (ITeamMembersCollectionPage)new List<ConversationMember>()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
},
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
Unfortunately, when I run the code, it shows:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[Microsoft.Graph.ConversationMember]' to type 'Microsoft.Graph.ITeamMembersCollectionPage'.'
I cannot make it work. The workaround is to use httpClient to send the request in your code.
See a similar question here.
UPDATE:
I have figured it out.
You can try the following code:
var team = new Team
{
DisplayName = "My Sample Team558",
Description = "My Sample Team’s Description558",
Members = new TeamMembersCollectionPage() {
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
},
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
If you prefer httpClient method, refer to this:
string str = "{\"template#odata.bind\":\"https://graph.microsoft.com/v1.0/teamsTemplates('standard')\",\"displayName\":\"My Sample Team999\",\"description\":\"My Sample Team’s Description555\",\"members\":[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce\"}]}";
var content = new StringContent(str, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = client.PostAsync("https://graph.microsoft.com/v1.0/teams", content).Result;
UPDATE 2:
If you need to call it in Postman, use this format:
{
"template#odata.bind":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
"displayName":"My Sample Team555",
"description":"My Sample Team’s Description555",
"members":[
{
"#odata.type":"#microsoft.graph.aadUserConversationMember",
"roles":[
"owner"
],
"userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
]
}

How to read username(DisplayUserPrincipalName) from Azure AD B2C using graph API?

I am trying to read username from Azure AD for a logged-in user using Microsoft Graph API, but I am getting only Name and UserPrincipalName which is some kind of {Guid}-#{tenant}.onmicrosoft.com. Below is my code snippet.
appsetting.json file
"Authentication": {
"AzureAdB2C": {
"Instance": "************",
"ClientId": "********",
"Tenant": "********",
"SignUpSignInPolicyId": "B2C_1_SignUpSignIn",
"ResetPasswordPolicyId": "B2C_1_PasswordReset",
"EditProfilePolicyId": "",
"RedirectUri": "/signin-oidc",
"ClientSecret": "*************"
}
}
public class AzureADProfileResponse
{
public string userPrincipalName { get; set; }
public string surname { get; set; }
public string displayName { get; set; }
public string givenName { get; set; }
}
Get Token for Graph API
public async Task<string> GetTokenAsync()
{
var clientId = _configuration.GetValue<string>("Authentication:AzureAdB2C:ClientId");
var app = PublicClientApplicationBuilder.Create(clientId).Build();
var accounts = await app.GetAccountsAsync();
string[] Scopes = { "User.Read" };
string token = null;
var authResult = await app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()).ExecuteAsync();
token = authResult.AccessToken;
return token;
}
Reading the config
private AzureTenant GetTenantDetailsFromConfig()
{
return new AzureTenant
{
Tenant = _configuration.GetValue<string>("Authentication:AzureAdB2C:Tenant"),
ClientId = _configuration.GetValue<string>("Authentication:AzureAdB2C:ClientId"),
ClientSecret = _configuration.GetValue<string>("Authentication:AzureAdB2C:ClientSecret")
};
}
Getting profile details for logged-in user
public async Task<AzureADProfileResponse> GetProfileDetails(AzureADProfileRequest azureAd)
{
var appValues = GetTenantDetailsFromConfig();
string url = "https://graph.microsoft.com/v1.0" + "/users" + "/" + azureAd.UserId ;
var accessToken = GetAzureToken(appValues.ClientId, appValues.ClientSecret, appValues.Tenant).Result;
using (HttpClient httpClient = new HttpClient())
{
using (HttpRequestMessage apiRequest = new HttpRequestMessage(HttpMethod.Get, url))
{
apiRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (HttpResponseMessage apiResponse = httpClient.SendAsync(apiRequest).Result)
{
var apiJsonResponse = await apiResponse.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AzureADProfileResponse>(apiJsonResponse);
}
}
}
}```
I am getting the other details and able to get UserPrincipalName which is in Guid format, but I require to read the username which is displayed in Azure AD for each of the users. Is there any way by which I can decode/read the displayUserPrincipal name for the logged-in user.
I am able to see the response under network tab in Azure AD for the below request https://main.iam.ad.ext.azure.com/api/Users/{objectId} with the displayUserPrincipalName.
I was getting a [GUID]#[tenant].onmicrosoft.com userPrincipalName, and was looking for the user's actual email address.
I was able to find it in the identities array, which you have to query specifically for in the graph api. It has a convenient signInType: 'emailAddress' attribute so you can easily find it programmatically.
Use the beta endpoint. The username is in the identities collection.
Microsoft Graph only provides MailNickName, UserPrincipalName, and mail.
Please refer the supported/list of Properties returned from Users List in this document.
You can get the UserPrincipalName with the below query
https://graph.microsoft.com/v1.0/users/userid?$select=userPrincipalName
Please refer similar Question

Identity Server 4 Checking for expected scope openid failed

I'm trying to set up an Identity Server for the first time in ASP.NET Core. I've set up everything to use a database and have created a script to create a test client, test user and resources. I can request a client token and request a user token, those work fine, but when calling the connect/userinfo endpoint, I'm getting a Forbidden response and the following error;
IdentityServer4.Validation.TokenValidator[0]
Checking for expected scope openid failed
{
"ValidateLifetime": true,
"AccessTokenType": "Jwt",
"ExpectedScope": "openid",
"Claims": {
"nbf": 1556641697,
"exp": 1556645297,
"iss": "https://localhost:5001",
"aud": [
"https://localhost:5001/resources",
"customAPI"
],
"client_id": "newClient",
"sub": "75f86dd0-512e-4c9d-b298-1afa120c7d47",
"auth_time": 1556641697,
"idp": "local",
"role": "admin",
"scope": "customAPI.read",
"amr": "pwd"
}
}
I'm not sure what is causing the issue. Here is the script I used to setup the test entities;
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
// API Client
Client client = new Client
{
ClientId = "newClient",
ClientName = "Example Client Credentials Client Application",
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("123456789".Sha256())
},
AllowedScopes = new List<string> {"customAPI.read"}
};
context.Clients.Add(client.ToEntity());
context.SaveChanges();
// Identity Resources
IList<IdentityResource> identityResources = new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource
{
Name = "role",
UserClaims = new List<string> {"role"}
}
};
foreach (IdentityResource identityResource in identityResources)
{
context.IdentityResources.Add(identityResource.ToEntity());
}
// API Resource
ApiResource resource = new ApiResource
{
Name = "customAPI",
DisplayName = "Custom API",
Description = "Custom API Access",
UserClaims = new List<string> {"role"},
ApiSecrets = new List<Secret> {new Secret("scopeSecret".Sha256())},
Scopes = new List<Scope>
{
new Scope("customAPI.read"),
new Scope("customAPI.write")
}
};
context.ApiResources.Add(resource.ToEntity());
context.SaveChanges();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
// User
IdentityUser user = new IdentityUser
{
UserName = "JohnDoe",
Email = "john#doe.co.uk",
};
IList<Claim> claims = new List<Claim>
{
new Claim(JwtClaimTypes.Email, user.Email),
new Claim(JwtClaimTypes.Role, "admin")
};
userManager.CreateAsync(user, "112222224344").Wait();
userManager.AddClaimsAsync(user, claims).Wait();
}
}
I'm sure I've set up something wrong when I set up the client/user, can anyone pinpoint what it is?
Can't see your client side code, but the error says you did not requested openid scope when applied for the token. The token valid for Useinfo endpoint must contain openid scope.

Azure function Graph API Insufficient privileges

I've created a C# function in Azure and it looks like this:
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using System.Text;
using Newtonsoft.Json.Linq;
public static async void Run(string input, TraceWriter log)
{
log.Info("---- Gestartet ----");
var token = await HttpAppAuthenticationAsync();
log.Info("---- Token: " + token.ToString());
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var user = "username#XXXXX.com";
var userExists = await DoesUserExistsAsync(client, user, log);
if(userExists)
{
log.Info("Der Benutzer existiert.");
}
else {
log.Info("Benutzer nicht gefunden.");
}
}
public static async Task<string> HttpAppAuthenticationAsync()
{
//log.Info("---- Start ----");
// Constants
var tenant = "2XXXXXCC6-c789-41XX-9XXX-XXXXXXXXXX";
var resource = "https://graph.windows.net/";
var clientID = "5XXXXef-4905-4XXf-8XXa-bXXXXXXX2";
var secret = "5GFzeg6VyrkJYUJ8XXXXXXXeKbjYaXXX7PlNpFkkg=";
var webClient = new WebClient();
var requestParameters = new NameValueCollection();
requestParameters.Add("resource", resource);
requestParameters.Add("client_id", clientID);
requestParameters.Add("grant_type", "client_credentials");
requestParameters.Add("client_secret", secret);
var url = $"https://login.microsoftonline.com/{tenant}/oauth2/token";
var responsebytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
var responsebody = Encoding.UTF8.GetString(responsebytes);
var obj = JsonConvert.DeserializeObject<JObject>(responsebody);
var token = obj["access_token"].Value<string>();
//log.Info("HIER: " + token);
return token;
}
private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user, TraceWriter log)
{
log.Info("---- Suche Benutzer ----");
try
{
var payload = await client.GetStringAsync($"https://graph.microsoft.net/v1.0/users/user");
return true;
}
catch (HttpRequestException)
{
return false;
}
}
In my log I get the bearer token. But then result of DoesUserExistsAsync is false.
If I send an request via Postman with the token I get following response:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "10XXX850-XXX-4d72-b6cf-78X308XXXXX0",
"date": "2017-09-07T14:03:58"
}
}
}
In the Azure AD I created an App and the permissions are:
(I gave all permisions only to test what`s wrong)
Since you're using client_credentials, there is no "user". That OAUTH grant only authenticates your application, not an actual user.
When using client_credentials, only the scopes listed under "Application Permissions" are applicable. Since you don't have a user authenticated, there isn't a user to "delegate" to your app.
Application Permissions are also unique in that every one of them requires Admin Consent before your app can use them. Without consent, your application will have insufficient privileges to complete any operation.
Also, this call won't return anything:
await client.GetStringAsync($"https://graph.microsoft.net/v1.0/users/user");
I assume what you're really looking for is:
private async Task<bool> DoesUserExistsAsync(HttpClient client, string userPrincipalName, TraceWriter log)
{
log.Info("---- Suche Benutzer ----");
try
{
var payload = await client.GetStringAsync($"https://graph.microsoft.net/v1.0/users/"
+ userPrincipalName);
return true;
}
catch (HttpRequestException)
{
return false;
}
}

Resources