Active Directory not returning groups for all users - azure-active-directory

I've built a node.js app with express and the passport-azure-ad library in order to authenticate users via AAD. I want to get groups back in the auth callback for users that are logging in so I can ensure they belong to the correct security group before granting them access to parts of my app.
I edited my manifest for my Active Directory App (Clarity) to include
"groupMembershipClaims": "All"
This is working very well for all users that I have had log in except for one. Typically I get a response in the profile object of this form:
accessToken: "scrubbedAccessToken"
aio: "scrubbedAio"
amr: "["pwd"]"
family_name: "My Last Name"
given_name: "My First Name"
groups: Array[1]
0: "[...hugeListofGuids...]"
length: 1
in_corp: "true"
ipaddr: "my ip"
name: "My Name"
oid: "scrubbedOid"
onprem_sid: "scrubbedSid"
sub: "scrubbedSub"
tid: "scrubbedTid"
unique_name: "myemail#microsoft.com"
upn: "myemail#microsoft.com"
ver: "1.0"
But for some reason for one of my users my app gets this instead:
_claim_names: "{"groups":"src1"}"
_claim_sources: "{"src1":{"endpoint":"https://graph.windows.net/scrubbedTid/users/scrubbedOid/getMemberObjects"}}"
accessToken: "scrubbedAccessToken"
aio: "scrubbedAio"
amr: "["pwd"]"
family_name: "scrubbedLastName"
given_name: "scrubbedFirstName"
in_corp: "true"
ipaddr: "scrubbedIp"
name: "scrubbedFulleName"
oid: "scrubbedOid"
onprem_sid: "scrubbedSid"
sub: "scrubbedSub"
tid: "scrubbedTid"
unique_name: "scrubbedEmail"
upn: "scrubbedEmail"
ver: "1.0"
Can anyone give me some insight as to why I'd get different formats for different users? These users are both in the same tenant and their emails are in the same domain.

The number of Group Membership Claims that are returned in the Access Token are limited based on the token type.
Take a look at this blog post: Azure Active Directory, now with Group Claims and Application Roles!
To ensure that the token size doesn’t exceed HTTP header size limits,
Azure AD limits the number of objectIds that it includes in the groups
claim. If a user is member of more groups than the overage limit (150
for SAML tokens, 200 for JWT tokens), then Azure AD does not emit the
groups claim in the token. Instead, it includes an overage claim in
the token that indicates to the application to query the Graph API to
retrieve the user’s group membership.
You are noticing a behavior which implies that this user is a member of too many groups, and you will need to call the AAD Graph API to get those details.

Related

Azure Active Directory B2C: How to query MS Graph to get a user's alternative security ID?

B2C uses an alternative security ID to uniquely identify users from social accounts. We have a problem where a user enters credentials for a user, but somehow B2C authenticates the user as someone else. I suspect the IDP is returning bad claims data or the alternative security IDs are the same. How do I view the alternative security ID of a user in Active Directory?
I tried the following MS Graph query trying all the attributes I can think of (including the ones listed in this article), but graph doesn't return data for these attributes.
https://graph.microsoft.com/v1.0/users/<userId>?$select=id,alternativeSecurityId,alternativeSecurityIds,extension_<b2cExtensionAppId>_alternativeSecurityId,extension_<b2cExtensionAppId>_alternativeSecurityIds
Thanks in advance!
AlternativeSecurityId for a B2C user is found in the Identities collection via MS Graph API.
The AlternativeSecurityId claim used in the B2C policy maps to the Identities: issuerAssignedId value for the corresponding issuer.
Eg, for issuerAssignedId: 123 (id from google token) from issuer: google.com
"identities": [
{
"signInType": "federated",
"issuer": "google.com",
"issuerAssignedId": "123"
}
],
You can return the identities collection by calling the /users endpoint of MS Graph API. https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http

How to solve "NoPermissionsInAccessToken" returned by Microsoft Graph when reading calendar or sending mail

Within our department we have a Classic ASP website that has been using our corporate Google accounts for authentication and to insert events into our Google Calendars. The organisation has just switched from Google to Office 365 and I'm trying to switch the code to use Outlook instead - with no success.
I can use the access token to GET https://graph.microsoft.com/v1.0/me and see the basic profile, but if I try to read calendar events or send an e-mail I see the message:
"error": {
"code": "NoPermissionsInAccessToken",
"message": "The token contains no permissions, or permissions can not be understood."
I created an Azure account with my personal Microsoft account and added an application. I added my colleagues and my corporate account as guest users. I set the permissions required and did the admin consent thing:
I then followed the steps on this page.
I first visit https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize, including the following query items:
client_id={client id}
response_type=code
redirect_uri={our URL}
response_mode=query
scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
state={number}
This returns a "code", which I send to https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/token, including:
grant_type=authorization_code
client_secret={client secret}
client_id={client id}
scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
state={same number as above}
redirect_uri={same URL as above}
code={code returned from /authorize}
This returns the id, access and refresh tokens. If I decode the access token using https://jwt.ms/, it seems to contain the appropriate audience and scope:
"aud": "https://graph.microsoft.com"
"scp": "Calendars.ReadWrite email Mail.Send openid profile User.Read"
...although I notice that there is no "roles" entry, which I see in some of the documentation. Is that an issue?
I then send the access token to https://graph.microsoft.com/v1.0/me with the following headers:
"Authorization", "Bearer {access token}"
"Host", "graph.microsoft.com"
"Content-Type", "application/json"
"Prefer", "outlook.timezone Europe/London"
That will return my e-mail address, etc., but if I change the URL to anything else, such as /me/photo/$value, /me/calendar/events, or try to send an e-mail I'm told that there are no permissions in the token.
I see that there are other similar questions, but they are mostly for the client_credentials flow (I'm not sure that makes any difference), and none of the answers has helped me resolve my problem.
Can someone please let me know if I've obviously missed anything - or I'm going about this in the wrong way to access Graph data on the client side? It seemed so straightforward with Google, but I'm finding the Microsoft documentation and examples a bit less detailed.
Adding guest users is meaningless.
What you have done is Admin consent for the Azure AD with your personal Microsoft account.
What you actually need to do is Admin consent for the target Azure AD/ O365 tenant.
Construct a consent link as following:
https://login.windows.net/{tenant ID of the target Azure AD}/oauth2/authorize?response_type=id_token&client_id={client ID}&redirect_uri={reply url}&response_mode=form_post&nonce=a4014117-28aa-47ec-abfb-f377be1d3cf5&resource=https://graph.microsoft.com&prompt=admin_consent
Access it in a browser and log in with an admin account of target Azure AD.
Another issue is that you are using Get access on behalf of a user. So you have to assign Delegated permissions rather than Application permissions in the Azure AD app.

How to check if a user is in an AD group via Azure AD?

Setup Specifications
.NET 4.5.1 MVC Project
Project contains .aspx files (legacy)
Currently user Azure AD for authentication via Cookies.
Azure portal configured (via App Registrations) with "Implicit Grant - ID Tokens" and "Accounts in this organizational directory only"
On-Premise AD groups are pushed up to Azure AD.
Startup.cs Configuration
// COOKIES: Tells it to use cookies for authentication.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieManager = new SystemWebCookieManager()
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
ClientId = ClientID,
Authority = Authority,
PostLogoutRedirectUri = PostLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = PrincipalService.OnAzureAuthenticationFailure,
AuthorizationCodeReceived = (AuthorizationCodeReceivedNotification notification) =>
{
var username = notification.AuthenticationTicket.Identity.Name.Split('#').LastOrDefault();
var emailAddress = notification.AuthenticationTicket.Identity.Claims.FirstOrDefault(x => x.Type.Contains("emailaddress"))?.Value;
Logger.Log(Level.Auth, $"Azure login success! Username: '{username}' Email: '{emailAddress}'.");
return Task.FromResult(0);
}
}
});
Question
How can I, given this setup, check if the currently logged in user is in a particular AD Group?
What I've tried
All the guides on doing Microsoft Graph API always come up with a problem that I don't know how to get past (e.g. GetAccountsAsync returning empty, etc).
I added the following to our app registration manifest:
"optionalClaims": {
"idToken": [
{
"name": "email",
"source": null,
"essential": true,
"additionalProperties": []
},
{
"name": "groups",
"source": null,
"essential": true,
"additionalProperties": []
}
],
"accessToken": [],
"saml2Token": []
}
email works fine, but obviously groups doesn't as it was a shot in the dark.
1. Getting Group Membership Claims as part of Token
You can enable group claims to come in as part of the access token for your application by editing your application's manifest (this can be done directly in Azure Portal) and setting "groupMembershipClaims" property to "All" or "SecurityGroup" as needed.
2. Group Ids are returned as part of Claims
Once application manifest is updated as mentioned above, you can get Group Id's as part of claims. Here's a quick sample for a decoded JWT token
3. Limit on the number of groups that can be returned as part of token
To ensure that the token size doesn't exceed HTTP header size limits, Azure AD limits the number of objectIds that it includes in the groups claim. If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens), then Azure AD does not emit the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the Graph API to retrieve the user's group membership.
4. Relevant Microsoft Graph APIs
NOTE: Working with Microsoft Graph APIs can be pretty powerful, since you can get around overage scenarios as well as get all other kinds of information about groups if needed (like name). In this particular case, since intent is to validate group membership, group Id is the best field as it will not change while others like name can.
Check member groups
This one will be helpful if you already know the groups that you want to check/validate membership in.
POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/checkMemberGroups
In request body, you can provide groupdIds, i.e. a collection that contains the object IDs of the groups in which to check membership. Up to 20 groups may be specified.
{
"groupIds": [
"fee2c45b-915a-4a64b130f4eb9e75525e",
"4fe90ae065a-478b9400e0a0e1cbd540"
]
}
user: getMemberGroups
This one will be helpful if you don't already know the group and want to get all the groups that this user belongs to.
POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/getMemberGroups
Here is another related SO Post

"One or more scopes are not compatible with each other" error when retrieving access token for the

I have an app that integrated with Outlook, Calendar via the Azure AD REST API v.2. I have tried to use the incremental and dynamic scopes to "upgrade" the user's token so that the app can access OneDrive as well, (so the user could directly upload her email attachments in her cloud).
The authorization code retrieval redirects went well and the user is asked for the additional scope after login (files.readwrite). However, on step 2 when I try to obtain the access token I get the following error:
System.Exception: Acquire token by authorization code returned BadRequest:
{
"error": "invalid_scope",
"error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. One or more scopes in 'https://outlook.office.com/mail.readwrite https://outlook.office.com/mail.send https://outlook.office.com/contacts.readwrite https://outlook.office.com/calendars.readwrite https://outlook.office.com/people.read files.readwrite' are not compatible with each other.\\r\\nTrace ID: b02fa0bf-6e86-4156-81e8-294dbc851500\\r\\nCorrelation ID: 3697bd18-554c-47e6-81cc-de3c47780fc9\\r\\nTimestamp: 2018-02-01 15:26:10Z",
"error_codes": [
70011
],
"timestamp": "2018-02-01 15:26:10Z",
"trace_id": "b02fa0bf-6e86-4156-81e8-294dbc851500",
"correlation_id": "3697bd18-554c-47e6-81cc-de3c47780fc9"
}
Or this error:
System.Exception: Acquire token by authorization code returned BadRequest:
{
"error": "invalid_request",
"error_description": "AADSTS700022: The provided value for the input parameter scope is not valid because it contains more than one resource. The scope https://outlook.office.com/mail.readwrite https://outlook.office.com/mail.send https://outlook.office.com/contacts.readwrite https://outlook.office.com/calendars.readwrite https://outlook.office.com/people.read files.readwrite is not valid.\\r\\nTrace ID: 9781d206-11b3-46c8-b972-8c4e77641c00\\r\\nCorrelation ID: 7e63af89-6e95-45f4-abaa-8f32051fb9ef\\r\\nTimestamp: 2018-02-01 15:36:32Z",
"error_codes": [
700022
],
"timestamp": "2018-02-01 15:36:32Z",
"trace_id": "9781d206-11b3-46c8-b972-8c4e77641c00",
"correlation_id": "7e63af89-6e95-45f4-abaa-8f32051fb9ef"
}
I assume I can't use the same token for both Outlook and OneDrive access because they are "different resources", one being part of the Office 365 and the other in Microsoft graph, however, I struggle to find a comprehensive list of which resources are compatible with which in here (https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-scopes).
My question is, does this mean that I will need to maintain 2 different tokens (my app uses the offline scope to refresh the token) for OneDrive and Outlook?
Also is there a difference between OneDrive for a personal account and OneDrive for a business accounts (which I think is the same as Sharepoint)? When working with outlook I can use the same code for outlook.com and Office365 emails, but I am not sure this is the case when it comes to working with files.
With the Google APIs it's quite simple to just add the Google Drive (or any other API) scope to your Gmail access scopes, but I guess that's not the case with the Microsoft APIs.
Thanks
Yes you will need two tokens. As juunas said in his comment, the problem is the audience, or the aud parameter in the token. You're asking for scopes that apply to two different audiences: https://outlook.office.com and https://graph.microsoft.com.
The good news is that these two APIs do have overlapping scopes, and Azure AD will allow you to use a refresh token issued for Graph to get a token for the Outlook API. So here's what I suggest (assuming you're doing authorization code flow)
Do your authorization request using Graph scopes:
mail.readwrite
mail.send
contacts.readwrite
calendars.readwrite
people.read
files.readwrite
Do a token request with grant_type=authorization_code using those same Graph scopes. This gets your Graph token + refresh token.
Do a token request with grant_type=refresh_token using the refresh token from previous step, but this time with ONLY the Outlook-applicable scopes, qualified for https://outlook.office.com. This gets your Outlook token.
https://outlook.office.com/mail.readwrite
https://outlook.office.com/mail.send
https://outlook.office.com/contacts.readwrite
https://outlook.office.com/calendars.readwrite
https://outlook.office.com/people.read

How to get Azure tenant name from graph.microsoft.com?

I need to discover user's tenant name, since the service endpoint, resourceId that I'll be using an Azure service that requires me to specify the tenant name:
service endpoint: https://[tenantnamme].api.crm.dynamics.com/...
resource Id: https://[tenantname].crm.dynamics.com
I was hoping Unified Microsoft Graph API can discover this for me. I looked at the documentation, the closest I can see is to use
graph.microsoft.com/v1.0/organization
which will give me back:
verifiedDomains : [
....
"name" : "contoso.onmicrosoft.com"
]
But, I'm not sure if this is the right approach. What if an org has multiple verified domains? Does verified domain name is the same as tenant name?
Update: This is my real scenario. I have a web app that allows user to authenticate to Azure AD via OAuth2. I have no problem obtaining refresh token and access token from OAuth interactions. However, in other to use other service, it requires [azure-ad-tenant-name] in their service end point. That's my question coming from.
I believe that you're on the right track with the graph.microsoft.com/v1.0/organization endpoint. You should be able to find the tenant name in the verifiedDomains list. The entry that should contain domain with the tenant name is the initial domain:
{
...
"isInitial": true,
"name": "contoso.onmicrosoft.com",
...
}
Same. When you create a AD, you will obtain a domain name and a tenant id without tenant name, they are both the unique identifier of a AD. Use Get-AzureRmTenant to get all tenantid and domains in your subscription.

Resources