Access token validation failure. Invalid audience - azure-active-directory

I need help in the context of error = I am getting "message": "Access token validation failure. Invalid audience.",
I am using the Authorisation code grant type in Oauth.
I have mapped custom claims to the app using Azure AD policy. So If I user Scope = AppId/.default then I get a custom claim in token and scope what APP has API permission on Azure AD such as user.read, directory.read. But with this when I call graph API for a user profile to see a member of "https://graph.microsoft.com/v1.0/me/memberOf" I get error "Invalid audience"
However, If I use scope = https://graph.microsoft.com/.default
Then I am able to query though custom claim which is mapped to App does not come up.
Any help would be appreciated?

Tokens can only have one audience, which controls which API they grant access to. The token for your app/API cannot be used for Graph. It isn't clear what your exact scenario is here, but if you're calling Graph from your app/API, you may want to look at the on-behalf-of flow to exchange your first token for a Graph token.

Related

Invitations API returns 401 Access token validation failure. Invalid audience

I have an MSDN subscription linked to my Personal account. I am trying to write and Web Application which can invite users users using the Invitation API, https://graph.microsoft.com/v1.0/invitations.
I tried to get an token using the Client Credentials flow and then call the above API but getting an invalid audience error. I checked the token and the aud claim is set to 00000002-0000-0000-c000-000000000000 which i think is Graph API. I set the Scope as https://graph.microsoft.com/.default while getting the token
Can some one help me what is that i am doing wrongly or is this scenario not supported
Since you are trying with your personal account which is not supported at this moment as you could see on screenshot below:
You could have a look on official document here
I have tried below way and worked for me:
Request:
{
"invitedUserEmailAddress": "kironTest#email.com",
"inviteRedirectUrl": "https://myapp.com",
"userType":"Guest"
}
Response:
Make sure your token has required permission like below:
You could check your permission here https://jwt.io/
Hope that would help.

Azure Graph API giving error "Auth token does not contain valid permissions or user does not have valid roles"

I have been trying to list Microsoft Security Scores, following official instructions provided here
but I keep getting an error:
Auth token does not contain valid permissions or user does not have valid roles.
Auth token is being requested once the user has loged in and provided the consent to my registered application. Application has all of the required permission as described in the official documents: SecurityActions.Read.All, Subscription.Read.All, User.Read.All
Currently I am trying this in React.jS however I have tried this process in Postman and Node as well but I am still stuck.
const accessToken = await this.userAgentApplication.acquireTokenSilent({
scopes: config.scopes
});
const securityScores = await getSecureScores(accessToken);
if(securityScores && securityScores.value){
this.setState({
securityScores: securityScores
});
}
and scopes array looks like this:
scopes: [
'Directory.Read.All',
'AccessReview.Read.All',
'offline_access',
'Organization.Read.All',
'Policy.Read.All',
'profile',
'SecurityActions.Read.All',
'Reports.Read.All',
'SecurityEvents.Read.All',
'User.Read',
'User.Read.All'
]
It's a known issue. This error occours when you are using Implicit grant flow.
There is not a wids field in the access token obtained through the implicit flow. Based on the document, it may not be present in tokens due to token length concerns.
There are two workarounds.
Once the response mode is changed to response_mode=form_post the id
token, and access token if requested, are sent as a POST request and
contain the wids claim which allows the Graph API security endpoints
to be used.
Do an OBO call to get a token for Graph, then call graph to learn
what they wids or roles are on the token. You can also do OBO to get
an id_token which should have those claims in it.
See a previous discussion here. And you need to pay attention to rayterrill's answer and hpsin's answer.

ID tokens vs Access tokens in implicit grant flow

I would like some clarification on how to use ID tokens and access tokens in an implicit grant flow.
I have an Angular SPA using MSAL.js for Angular package and a Web API. The API does NOT call any external services, like MSFT Graph. The back end uses role claims from JWT to establish RBAC authorization to our API functionality only.
This doc says:
https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens
id_tokens are sent to the client application as part of an OpenID Connect flow. They can be sent along side or instead of an access token, and are used by the client to authenticate the user.
ID Tokens should be used to validate that a user is who they claim to be and get additional useful information about them - it shouldn't be used for authorization in place of an access token.
This doc shows an authentication flow where a web API is called with an ID token instead of an access token:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
This sample code sends ID token too (calling own Web API sample):
https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi-v2
The sample back end validates ID token audience against Client ID of the app that issued it.
Given our API is the only consumer of tokens, should we use ID tokens or access tokens?
Generally speaking, when securing your API with the Microsoft Identity platform, clients should be using the access token when making API requests, not the ID token.
check this part
It first calls acquireTokenSlient, which gets a token from the cache if available if not
it calls acquireTokenPopUp which will get an acces token for the specific scope, I am not sure if it would open up a popup window or will get a token in the background with hidden iframe. But it would fetch an access token for sure. API can never be accessed with ID token.
check https://learn.microsoft.com/bs-latn-ba/azure/active-directory/develop/scenario-spa-acquire-token for more clarification

invalid_grant error when obtaining access token

I am trying to build a website where a user can log in via Azure AD B2C. After logging in, I'm trying to present a secure area where the user can change their Azure B2C user attributes (first name, last name, etc) via the Microsoft Graph API.
I am attempting to follow along with the Get a Token documentation
Everything is working up to step #3, where a call gets made out to https://login.microsoftonline.com/common/oauth2/v2.0/token to obtain an access_token using the code I received on my return URL.
Here's the general flow of what I am doing:
End user clicks a login link on my localhost site that links out to my Azure B2C tenant policy. Link looks something like this:
https://login.microsoftonline.com/mytenantname.onmicrosoft.com/oauth2/v2.0/authorize
?client_id=[MyAppID]
&response_type=code+id_token
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.write
&state=[MyCustomState]&p=[MyCustomPolicy]
User logs in and gets redirected to the redirect_uri.
redirect_uri successfully recieves code, id_token, and state values.
I take the code value from that and makes a POST https://login.microsoftonline.com/common/oauth2/v2.0/token request with the following body:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
HTTP/1.1
grant_type=authorization_code
&code=[code]
&client_secret=[application secret]
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.readwrite
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
The response code I receive back from that endpoint is the above error message.
{
"error": "invalid_grant",
"error_description": "AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID:6d7a8e32-bcbf-4fc4-a37a-87dae4781b00\r\nCorrelation ID:252912b7-5775-491a-968f-00ab03696dd9\r\nTimestamp: 2019-06-2722:11:18Z",
"error_codes": [9002313],
"timestamp": "2019-06-27 22:11:18Z",
"trace_id": "6d7a8e32-bcbf-4fc4-a37a-87dae4781b00",
"correlation_id": "252912b7-5775-491a-968f-00ab03696dd9"
}
Other StackOverflow posts mention verifying that the redirect_uri's have to match between the initial login and the subsequent access_token requests. They appear identical to me, but I am still receiving errors.
Any ideas what could be going wrong?
This is something you need to understand about OAuth on B2C before you are able to successfully request for a token.
This error means that the requested scope (resource) can’t be accessed by you (login user) because of the lack of permissions.
So, to fix that, you need to grant these required permissions to access that resource, by following these steps:
Define a new scope.
Grant Admin consent on that scope.
Request that scope when you request for a token.
In other words, in B2C-->App Registrations--> (Your App), shown in the image below, start with “Expose an API”, here you define a new scope of access, scope of resources or API, just a metadata that you know it represents some resources or API.
Then you click on “API Permissions”, here you will add the scope you just created and grand admin access in needed. But al least you need to add permissions to your newly defined scope.
The third and last step is when you hit: https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/token
Make sure to pass the scope that you added. (Use the scope that you added)
The details are explained in here but I can simplify it for you.
configure b2c
So you need to go to your B2C
Seems you are trying to get access token using Authorization Code Grant V2.0
Your request doesn't match with Authorization Code Grant V2.0 format and you have encountered that error.
You should send token request for Authorization Code Grant V2.0 is like below:
Token Endpoint: `https://login.microsoftonline.com/common/oauth2/v2.0/token`
client_id:b603c7be-_YourApp_ID-e6921e61f925
scope:https://graph.microsoft.com/User.ReadWrite.All
redirect_uri:https://www.getpostman.com/oauth2/callback
grant_type:authorization_code
client_secret:Vxf1SluKbgu4P_YourAppSecret_DSeZ8wL/Yp8ns4sc=
code:OAQABAAIAAADCoMpjJXrxTq9VG9te-7FXrnBIp82sWR1nC
See Screen shot for details:

How can I pull various claims out of the access token?

I'm using the msal.js library to connect to Azure AD B2C for a reactjs client application.
I can login and get the access token. I can dump that token into jwt.io and see the claims that I've specified in my sign in policy. But I'm missing how I can pull the claim data out within the application.
Does the msal library have a method to extend the user to include those claims?
Looking at the examples to get the user's name I'm thinking something like...
clientApplication.getUser().myCustomClaim
Alternatively does anyone have any suggestions on the best way to pull that claim data out of the token?
EDIT: Referenced the "dev" commit.
In the "dev" branch, this commit adds the idToken property to the User object.
You can reference the identity token claims as follows:
clientApplication.getUser().idToken["mycustomclaim"]

Resources