Issue in generating token with scope in Microsoft AAD using react. (401 Unauthorized) - reactjs

I am using react-aad-msal and msal packages for implementing authentication using azure active directory. I am able to get the access token but every time the token is validated as "Invalid token" by back-end(.net core). Server is throwing error below error.
System.UnauthorizedAccessException: Neither scope or roles claim was found in the bearer token.
I am able to access all web services by authenticating with response_type "code" in postman.
I have tried to decode the token in jwt.io. It is clearly the issue with scope. I am attaching the image of config file in react.
config
In the image, the blurred part in blue color is clientId from AAD app.
In above config, I have provided the scope, but after decoding the token I am not getting the scope field.

You cannot directly request /common, because it will not be able to respond to your scope or role because you can't find the tenant you want to request the token. You should add your tenant URI (domain.onmicrosoft.com) or tenant id when requesting .
https://login.microsoftonline.com/{your-tenant-uri-or-your-tenant-id}/oauth2/v2.0/token

Related

Two identical Azure apps with different access_token format - one JWT, the other non-JWT

When accessing /.auth/me, one app has the access_token in the correct JWT format, but in the other app it's not in JWT format.
This is the valid JWT one: eyJ0eXAiOiJKV1QiLCJu...eyJhdWQiOiJodHRwczov...B84ciSKwF2oOre5n
This is the non-JWT one: PAQABAAAAAAD--DLA3VO7QrddgJg7WevrTLy
The configuration for both apps appear to be identical.
Any idea how to fix the second app to also show JWT access token?
Usually when the authentication flow configuration has not included resource
as one of the parameter, the access token does not have form of a (
JSON Web Token)JWT token token format.
Please try to include resource with your application Id Uri or
resource that your application requires . To find the App ID URI, in
the Azure portal, click Azure Active Directory, click App
registrations, click the service application, and then click Settings
and Properties.
Also set the clientId and client secret in the request.
In other cases just to access the app service you could use id_token or Bearer as response_type in authorization header as Authorization:Bearer "{your-id-token}".
Reference:Oauth 2.0 grant credentials ,Access token request | Microsoft Docs
You can make use of azure resource explorer to edit the properties of the app service auth to include the resource if not already included. See resource provider and types
To get an access token, please try to set the resource using the Azure Resource Explorer.
Navigate to the Resource Explorer from the App Service.
Go to config > authsettings and click on Edit.
Update the additionalLoginParams with ["resource=<Name/ID of the resource>"] and click on PUT.
For example:
“additionalLoginParams”: [
“resource=https://graph.microsoft.com ”
]
Then by saving changes and refreshing the App Service, try again and check that the value for the access token is in the form of a JWT token or not.

Getting access tokens from Postman: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests

We recently made a switch from Implicit Grant Flow to Authorization Code Flow with PKCE for our application, and now we're having some trouble getting access tokens from Azure AD from Postman. The app is registered in Azure AD and we're basically using the Postman procedure described here: https://developer.mypurecloud.com/api/rest/postman/index.html#enable_authorization. Calling the https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize endpoint works ok, but it hits an error when calling https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token:
"Error: Cound not complete OAuth 2.0 token request: "AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests.\r\nTrace ID: 8253f622-3425-4d0a-817c-281f86097300\r\nCorrelation ID: 9d84460f-ec02-4ace-af03-14d948e3d4ad\r\nTimestamp: 2020-04-15 14:02:03Z"
This is the access token request:
How can we get access tokens from Azure AD using Postman with this authorization flow?
Apparently this is a problem as the documentation is confusing.
Over the Azure Active Directory App Registration. Make sure you add the redirect url over the "Mobile and desktop applications" category.
When you read the documentation looks like you need to add the Redirect URL under the Single Page Apps. It even shows confirmation message saying "Your Redirect URI is eligible for the Authorization Code Flow with PKCE." but is not true.
This error can occur when the "Origin" header is missing from the request (see: GitHub comment).
Try adding the header:
Origin: http://localhost
If you're experiencing this failure whilst trying to authenticate using Postman, ensure that you have a platform authentication for Web.
Go to Azure AD > App Registrations > {your app reg} > Authentication > Add a platform. Redirect URI should be https://oauth.pstmn.io/v1/callback when using the browser.
For me I was trying update the MSAL v1 implementation to v2 implementation where I got this issue. After doing migration from web to SPA in the Azure where it clearly takes about the same fixed my issues.
https://learn.microsoft.com/en-us/answers/questions/315313/azure-app-registration-causing-the-following-error.html
https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-browser#implicit-flow-vs-authorization-code-flow-with-pkce
To get an refresh_token you have to add "offline_access" to the scope.
The documentation of the response to the access token request says:
An OAuth 2.0 refresh token. The app can use this token acquire additional access tokens after the current access token expires. Refresh_tokens are long-lived, and can be used to retain access to resources for extended periods of time. For more detail on refreshing an access token, refer to the section below.
Note: Only provided if offline_access scope was requested.
Documentation
I was able to resolve this by doing the following:
Within the Azure Portal:
Navigate to the App Registration that you are using for your protected API.
Next, navigate to the Authentication blade within the Manage menu.
Within your Single-page application platform, add the following Redirect URI, https://oauth.pstmn.io/v1/callback.
Save these changes within the Azure Portal.
Next, within Postman's New Token Configuration:
Manually set the Callback URL to the same URI specified above (i.e. https://oauth.pstmn.io/v1/callback).
Once the above are done, clear your cookies from within Postman, and re-attempt retrieval of the token.
Follow these steps:
In your registered app, add platform for mobile and desktop application like below image:
Get your code which will be redirected to https://login.live.com/oauth20_desktop.srf?code=<code>.
If you are using Postman to get token so cross origin issue chances can be there. So try below php code to get token:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://login.microsoftonline.com/{tenenat-id}/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"grant_type=authorization_code&code={auth-code}&client_id={client-id}&scope=https%3A%2F%2Fmanagement.azure.com%2F.default&redirect_uri=https://login.live.com/oauth20_desktop.srf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
var_dump($server_output);
1.You should first get the code in the browser,Enter the following request information in the browser address bar:
2.Then enter the obtained code and other request information in postman, you will get the access token
3.Please check: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

Swaggerbuckle with AAD --Error AADSTS500013: Resource identifier is not provided

I'm trying to use AzureAD to get a token in swagger and test my .netCore2.1 API with it.(using Swashbuckle.AspNetCore 4.0.1)
To do this I completed the following steps
1. Created a Web API project(asp.net Core2.1)
2. Register an Azure AD (AAD) app for the Web API
3. Updated the Web API project to use Azure AD authentication
4. Register an AAD app for the Swagger web site https://localhost:5001/swagger
5. Granted permissions for the Swagger AAD app to access the Web API AAD app
6. Generated a Client Secret for the Swagger AAD app
7. Enabled OAuth2 implicit flow on the Swagger AAD app
8. Added Swagger to the Web API project
When I authenticate, I am getting the following error.
Error AADSTS500013: Resource identifier is not provided .
When I click authorize
I am getting error AADSTS500013: Resource identifier is not provided.
My WebAPI project's startup.cs file goes here
Please help me understand which resource Identifier I am missing here or how to resolve this error.
Or any pointers on how to use Swaggerbuckle with ASP.NET Core webAPI, especially with AAD authenticated WebAPI ?
UPDATES
I copied my webAPI's APPID URI from azure portal. ie Dashboard>>Microsoft - App registrations>>MY_API_APP>>Settings>>Properties>>App ID URI
But I am still getting the same error when I try to authenticate
Error AADSTS500013: Resource identifier is not provided
Usually resource identifier which uniquely identifies your application. You can easily found your resource Identifier Like below:
When logged into the Azure portal, Azure Active Directory > App Registrations > [App Name] > Settings> Properties, then it's the App ID URI
See the screen shot:
In the orignal OAuth 2.0 specification, there is no resource parameter in the authorization request. It use scope parameter. The authorization and token endpoints allow the client to specify the scope of the access request using the "scope" request parameter.
As document explains, when Azure AD implement the OAuth 2.0(1.0 endpoint), the resource is used to specify the access_token you request for which resource. And the Azure AD will issue the token which the scp based on the permission you config on the portal for the resource.
And in the v2.0 endpoint, the Azure AD also use the scope to support the dynamic permission request. More detail you can have a look here.
Usual Reason for Error
Make sure you have configured below steps accordingly.
Like below:
Application Manifest
Reply URI
Request Endpoint
For V1.0 refer this URI https://login.microsoft.com//oauth2/authorize
For V2.0 refer this URI https://login.microsoft.com//oauth2/v2.0/authorize
Application Consent
Need to confirm your application required resource access permission you could refer here
I believe this step can lead you to sort out your problem.
With Azure AD V1.0 app you need set resource to identify which api you want to access during the authentication&access token requests :
Code flow :
https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code
Implicit flow :
https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-implicit-grant-flow
In Swashbuckle.AspNetCore 4.0.1 , you need to config the resource as parameter if you want to get access token for accessing your web api :
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MySite API V1");
options.OAuthClientId("19c73866-562f-482a-bafb-89d9fe9b0aaa");
options.OAuthAppName("Swagger Api Calls");
// add resource
options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { { "resource", "f479db30-9b62-431b-98c2-bcaae52203cf" } });
});
For us Nan Yu's response got us one step closer.
We added the resource in the AdditionalQuerystringParams like so:
options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { { "resource", "{ResourceIDHere}" } });
We are now able to get passed the Auth step in Swagger, but trying routes out doesn't seem to pass the token to the api called and so we get a 401 Error.
change { "scope", API_AppID_URI} to { "resource", API_AppID_URI}

Acquiring a token for graph.microsoft.com with adal.js

I've been using Azure Active Directory and adal.js to authorize web apps client side and it's worked great. Recently had a request to have user photo instead of a generic user icon.
I added Microsoft Graph permissions to the app registration. And tried to get a token for the user photo request like...
authContext.acquireToken('https://graph.microsoft.com', callback);
Which resulted in the response_type 'token' is not supported for the application error. So I found ADAL JS - response_type="token" is not supported suggesting setting "oauth2AllowImplicitFlow": true in the app manifest, which I did. Now I get Token renewal operation failed due to timeout error.
I've also added 'https://graph.microsoft.com': 'https://graph.microsoft.com' to the endpoints prop of the context config.
What do I have to do get this working? Way too much time spent just trying to get users' photos. Thanks.

Postman - how to obtain Azure Active Directory token using sign in form?

Is is possible to obtain an AAD token in Postman by letting the user to Sign In using the standard AAD sign in form?
I know how to obtain token using the request to AAD (grant_type = client_credentials) but such a token does not have a UPN (user identity).
I would like to somehow type in my credentials in Postman and get the token. So it is a manual interaction, the user(me) needs to manually sign in - the same way how ie. Visual Studio verifies your identity.
Postman now offers the ability to "Authorize using browser." You'll need to make changes to your AAD application to support it in addition to configuring Postman.
Configure your AAD application
Add a redirect URI to your AAD application for Postman to receive the authorization code. In the AAD Portal, navigate to your app registration, then to the "Authentication" tab, then add https://oauth.pstmn.io/v1/callback as a new redirect URI. This URI was provided by Postman when you check the ✅ Authorize using browser box (below) and is also documented on their website.
Configure Postman
You can set this up under "Authorization" for a single request, a folder of requests, or a Collection. Open the "Authorization" tab and select OAuth 2.0. Under the "Configure New Token" section, enter the following information:
Token Name: anything you want. I chose the name of the AAD application.
Grant Type: Authorization Code (With PKCE)
Callback URL: check the ✅ Authorize using browser box
Auth URL: copy this from the AAD portal under Overview > Endpoints (on top bar) > OAuth 2.0 authorization endpoint (v2). Mine looks like https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize
Access token URL: copy this from the AAD portal under Overview > Endpoints (on top bar) > OAuth 2.0 token endpoint (v2). Mine looks like https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token
Client ID: copy this from the AAD portal under Overview. It's also commonly referred to as an "Application ID" and is a GUID.
Client Secret: leave blank (not used by this grant type)
Code Challenge Method: SHA-256
Code Verifier: leave blank or provide your own
Scope: the scopes you're requesting in your token, separated by spaces
State: leave blank or provide a value such as a random GUID.
Client Authentication: Send as Basic Auth Header (not used by this grant type)
Refer to Postman's documentation on OAuth 2.0 options for more information.
Get a token
Click Get New Access Token to open the auth flow in your machine's default web browser. After authentication, it should redirect back to the Postman application and a new token will be created with the name you provided earlier for "Token Name." Select "Use Token" in the top-right corner of the popup to copy it into your current token. If the token expires and your requests start failing authorization (probably a 401 or 403 error), you can revisit this tab and get a new access token.
Occasionally, you may want to visit Current Token > Access Token > Manage Tokens > Delete > Expired tokens, otherwise you'll be inundated with nearly-identical tokens.
Postman cannot popup the sign in page as it only does HTTP requests. As you stated, it can do confidential client flows.
What you could do is hand-construct an auth request, sign in, and grab the auth code. Then take that auth code and drop it into the Postman authorization form, and let it hit the Azure AD token endpoint:
https://login.microsoftonline.com/common/oauth2/v2.0/token
The Azure AD protocol referene will be super helpful for you.
I think if you're wanting to quickly generate Access Tokens your best bet is to pick a framework/language and build a lightweight app that gets and logs tokens. Azure AD has a Python Flask sample for the v2 endpoint that takes 5 minutes to setup and could be converted to printing out access tokens. If you want to use v1, you can checkout the list of samples at the Azure AD developer guide.

Resources