Azure AD me profile - azure

I have error "Access token validation failure. Invalid audience."
For application set api permissions to offline_access, openid, profile, User.Read.
User start auth, go to MS auth site, ask about login, password and grand.
After exchange code to access token i well receive
{'token_type': 'Bearer', 'scope': 'offline_access openid profile User.Read', 'expires_in': '3906', 'ext_expires_in': '3906', 'expires_on': '1653988700', 'not_before': '1653984493', 'resource': 'my_azure_client_id', ....}
Then i try get profile for current user with this access token.
As result i have error "Access token validation failure. Invalid audience."
Help pease)
UPDATE
Configured permissions

The reason behind getting that error is because your token has wrong audience.
Please check what token you are using to call Graph API.
I tried to reproduce the same in my environment.
If you are using ID Token instead of Access Token, you may get error like below:
To know whether you are giving access token or id token, decode it in JSON Web Tokens - jwt.io.
For access token, aud claim will be "https://graph.microsoft.com" or "00000003-0000-0000-c000-000000000000"
For id token, aud claim will be "your_app_client_id"
Choose the access token carefully with aud as "https://graph.microsoft.com" while calling Microsoft Graph API:
To get profile for current user, you can make use of below query:
GET https://graph.microsoft.com/v1.0/me
I got the profile successfully using access token like below:
Replace your scope with https://graph.microsoft.com/.default while generating access token to avoid confusion.
Reference:
oauth 2.0 - Microsoft Graph API: Access token validation failure. Invalid audience - Stack Overflow
UPDATE:
In order to get authorization code, make the request by changing scope like below:
https://login.microsoftonline.com/your_tenant_id/oauth2/v2.0/authorize?
client_id=your_client_id
&response_type=code
&redirect_uri=xxxxxx
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345

Related

InvalidAuthenticationToken error using msal and graph api from sharepoint

I am using the example msal-react to authenticate and consume sharepoint services using their graph api, create an application on AAD with delegated permissions.
I am assigning the scopes "https://mytenant.sharepoint.com/.default" and I get the following error code: "InvalidAuthenticationToken" message: "Access token validation failure. Invalid audience." check the token I get on the JWT.io page .
Thank you very much for your support
You are using the graph API to perform CRUD operations for SharePoint sites, so you should get an access token for the graph API instead of the SharePoint REST API.
So please change your scope to: https://graph.microsoft.com/.default.
I tried to reproduce the same in my environment via Postman and got below results:
I registered one SPA application and added SharePoint API permissions like below:
I generated access token via Postman with below parameters:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:appID
grant_type:authorization_code
scope: https://mytenant.sharepoint.com/.default
code:code
redirect_uri: https://jwt.ms
code_verifier:S256
Response:
When I decoded the token, it has SharePoint as audience and scp claim as below:
I got the same error as you when I used above token to call SharePoint from below graph API call:
GET https://graph.microsoft.com/v1.0/sites/<siteID>/lists
Response:
To resolve the error, assign Microsoft Graph API permissions for SharePoint like below:
Now, generate the access token again by changing the scope to https://graph.microsoft.com/.default as suggested by #Carl Zhao like below:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:appID
grant_type:authorization_code
scope: https://graph.microsoft.com/.default
code:code
redirect_uri: https://jwt.ms
code_verifier:S256
Response:
When I decoded the above token, I got Microsoft Graph as audience and scp claims are as below:
When I used above token to call SharePoint site lists from below graph API call, I got the results successfully like below:
GET https://graph.microsoft.com/v1.0/sites/<siteID>/lists
Response:
Note that, your token audience should be https://graph.microsoft.com while making graph calls and scp claim should contain Microsoft graph permissions.

User unauthorized though the token is correct

I'm trying to integrate D365FO with a third party application, I was able to do the proper setup and register my app, fetch the Token as shown below:
I used the resource as the link for D365FO at the development machine, which is https://usnconeboxax1aos.cloud.onebox.dynamics.com/ and read the D365FO data as shown below:
I want to change the login methid, so I do login on behalf of the user, using the password, so I Disabled thesecurirty details at Azure (based on this), as below:
And got teh token of the loged user successfult as below:
But once I tried fetching the same data which I was able to fetch before, I got 401 unauthorized, though I'm loggin in using the Admin account:
The error 401 Unauthorized usually occurs if you make calls to the resource with invalid audience.
When you generate the access token with scope as user.read openid profile offline_access, audience will be Microsoft Graph that won't work with D365FO.
I tried to reproduce the same in my environment via Postman and got below results:
I registered one Azure AD application and added same API permissions like below:
Now I generated tokens with grant type as password by including same parameters as you like below:
POST https://login.microsoftonline.com/organizations/oauth2/v2.0/token
client_id: <appID>
client_secret: <secret>
scope: user.read openid profile offline_access
grant_type: password
username: admin#xxxxxxxxx.onmicrosoft.com
password: xxxxxxxxxxx
Response:
You can decode the above access token by pasting it in jwt.ms to check the audience.
When I decoded the access token, I got aud claim as 00000003-0000-0000-c000-000000000000 (i.e, Microsoft Graph) like below:
If you use this token to read D365FO data, you will get 401 Unauthorized error as audience is invalid.
To resolve the error, you need to generate access token with resource value as base URL of your D365FO instance by making below changes:
POST https://login.microsoftonline.com/organizations/oauth2/token
client_id: <appID>
client_secret: <secret>
resource: <base URL of your D365FO instance without the trailing '/'>
grant_type: password
username: admin#xxxxxxxxx.onmicrosoft.com
password: xxxxxxxxxxx
In your case, value of resource parameter should be https://usnconeboxax1aos.cloud.onebox.dynamics.com
This token will have audience same as your D365FO root URL. To confirm that, you can decode it in jwt.ms. If you use this token to read D365FO data, it will work!
Reference:
Test services by using third-party utilities - Finance & Operations | Dynamics 365 | Microsoft

How to get access token using refresh token AzureAD

I want to get access token with the help of refresh token that I got previously.
I got tokens using scope: user.read offline_access openid in oauth2 endpoint:
https://login.microsoftonline.com/tenant.com/v2.0/token
After a couple of hours, access token expired. Now I am trying to get this using refresh token.
But I'm unsuccessful in it, any help is much needed.
I tried to reproduce the same in my environment and got below results:
I created one Azure AD application and added API permissions as below:
With below parameters, I got the tokens via Postman:
POST https://login.microsoftonline.com/tenantID/oauth2/v2.0/token
client_id:appID
grant_type:authorization_code
scope:https://graph.microsoft.com/.default
client_secret:client_secret
code:code
redirect_uri:https://jwt.ms
Response:
In order to get access token using above refresh token, change grant type to refresh_token.
I got the access token successfully using refresh token with parameters like below:
POST https://login.microsoftonline.com/tenantID/oauth2/v2.0/token
client_id:appID
grant_type:refresh_token
refresh_token: 0.AVYA_in0zaI3eUqOQHrbrD-FUv //paste the refresh token that you got above
client_secret:client_secret //Mandatory if client is web app
Response:

For IMAP.AccessAsUser.All Scope ADSTS65001: The user or administrator has not consented to use the application

In my java web application I want to get access to user's mailbox by using jakarta mail. For that purpose I followed https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth for OAuth2 authorization code flow.
On Azure port I setup my app and added API permissions as below
Now user is redirecting to below authorize endpoint:
https://login.microsoftonline.com/5426ee07-9b73-4a9e-8075-395ab439c6fa/oauth2/v2.0/authorize?client_id=b6067ad9-7195-430b-a35d-97b7aa7beb8f&response_type=code&redirect_uri=http://localhost:8080/callback/microsoft&response_mode=query&scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All%20https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send
After entering credentials and accepting the consent redirect_uri gets hit with auth code. Based on that auth code I formed token endpoint URL and hitting it from server, the token endpoint is as follow:
URL: https://login.microsoftonline.com/5426ee07-9b73-4a9e-8075-395ab439c6fa/oauth2/v2.0/token
Form Data:
client_id=b6067ad9-7195-430b-a35d-97b7aa7beb8f
scope=offline_access%20https%3A%2F%2Foutlook.office.com%2FIMAP.AccessAsUser.All
redirect_uri=http://localhost:8080/callback/microsoft
grant_type=authorization_code
client_secret=QUs8Q~aboLBiopTezMTKwzQjIwWsFFXjc2kCRaRs (I know I have shared the secret)
code={code received from authorize end point}
Response to this post request comes as:
{"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID 'b6067ad9-7195-430b-a35d-97b7aa7beb8f' named 'Email Connector'. Send an interactive authorization request for this user and resource.\r\nTrace ID: dc008ced-e23f-4919-bd45-b7ae7c68b000\r\nCorrelation ID: 9b6ede03-3c05-4a78-8975-036a3cb20773\r\nTimestamp: 2022-06-07 19:51:30Z","error_codes":[65001],"timestamp":"2022-06-07 19:51:30Z","trace_id":"dc008ced-e23f-4919-bd45-b7ae7c68b000","correlation_id":"9b6ede03-3c05-4a78-8975-036a3cb20773","suberror":"consent_required"}
Here, I don't understand why the error is saying The user or administrator has not consented to use the application, user has accepted the consent after entering credentials on authorize end point. Event more If we look at the screenshot above admin has already given grant to access the directory.
I tried to reproduce the same scenario in my environment and got the same error as below:
To resolve the error, please check the authorize endpoint you are using to get the code.
Avoid using Microsoft graph API scopes while getting the code.
Replace it with the scope you are using to get access token like below:
https://login.microsoftonline.com/Your_TenantID/oauth2/v2.0/authorize?
client_id=Your_ClientID
&response_type=code
&redirect_uri=http://localhost:8080/callback/microsoft
&response_mode=query
&scope= offline_access https://outlook.office.com/IMAP.AccessAsUser.All
&state=12345
Get the code from the above authorization endpoint.
I got the access token successfully after modifying the endpoint like below:
To validate the access token decode it in jwt.io and check the aud and scp claims like below:

Wrong access_token from AAD with OAuth2 flow

I am making OAuth 2.0 auth code authentication flow with multi-tenant application.
Here is my authorize url:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=my_id&prompt=consent&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauthorize&response_type=code&scope=openid+offline_access&state=17
It goes fine and I receive auth_code. Then I make request with this auth_code to token_url and receive a lot of information, like:
token_type
scope
id_token
access_token
refresh_token
expires_at
ext_expires_in
Seems fine to me, but when I make request on API with access_token like:
https://management.azure.com/subscriptions/my_sub_id/locations?api-version=2016-06-01
with headers:
Content-Type:
- application/json
Authorization:
- Bearer EwBQA8l6BAAURSN/FHlDW5xN74t6GzbtsBBeBUYAAV1IHgHb4dOWblzfd/YsSuFicAMDYbua17QivnAT9/pIaeKAg3uKsK5VGqWLzjMOUQrCpd7R1RAM6RkzI0u8e4rpO7DISG7qLso5H5+U1jb+38/j1urcwlXMMxhy83ZXmdpkLXpZV+vcOV...
It responds with 401 error
body:
encoding: UTF-8
string: '{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}'
To be honest I think something wrong with my access_token. It seems not like JWT for me. Documentation says it looks like:
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCEV1Q..."
But my access_token looks like:
"access_token": "EwBYA8l6BAAURSN/FHlDW5xN74t6GzbtsBBeBUYAAZDe7JE/MPLoAi+Fr+1Xxq5eBe5N9l8Q+c4QjkY5PGEzRnBpPe7+v6h+PLdh1cceBQx+/JsB2QCrYSCt7x/zGsQAhwoY/"
Is it fine?
Here is my permissions for application:
Permissions
The main issue you have here is that you have only asked for an access token for the scopes openid offline_access. The resulting access token will be for Microsoft Graph (https://graph.microsoft.com), not for the Azure REST API (https://management.azure.com).
To indicate you would like a token for a given API, the scope parameter in your authorization request should include the delegated permission you would like the app to have for the API. In the case of Azure REST API, there's only one delegated permission: user_impersonation. The identifier URI for the Azure REST API is https://management.azure.com, so the scope value you want to use is:
openid offline_access https://management.azure.com/user_impersonation
Two more important notes:
As you've discovered, you will not always be issued an access token as a JWT which you can decode peek at. The format of the access token is an agreement between the service which issued the token (Azure AD or Microsoft Accounts, in this case), and the service for which the token was issued (Microsoft Graph, in this example).
You should not always include prompt=consent. prompt=consent should only be used if you have already tried signing in the user without the user needs to be re-prompted for consent for a new permission.
If you simply include the required scopes in the scopes parameter, the Microsoft Identity platform will take care of figuring out if it needs to prompt for consent or not. If you always include prompt=consent, you will find that many organizations will be blocked from accessing your app, because they've disabled the ability for users to grant consent themselves (and this parameter specifically states that you require the user to be prompted again).

Resources