AADSTS65001: The user or administrator has not consented to use the application with ID <app-id>
Asked Answered
K

3

19

I'm developing an Angular + Flask application that uses Microsoft's OAuth2 (On-Behalf-Of-User Flow). I'm trying to call an API from the backend, but I get an exception.

Here is the configuration in app.module.ts:

export function MSALInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication({
    auth: {
      clientId: '<application_id_of_spa>',
      authority: 'https://login.microsoftonline.com/organizations',
      redirectUri: 'http://localhost:4200/'
    },
    cache: {
      cacheLocation: BrowserCacheLocation.LocalStorage,
      storeAuthStateInCookie: isIE,
    },
    system: {
      loggerOptions: {
        loggerCallback,
        logLevel: LogLevel.Info,
        piiLoggingEnabled: false
      }
    }
  });
}

export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
  protectedResourceMap.set('https://api.powerbi.com/v1.0/myorg/', ['https://analysis.windows.net/powerbi/api/.default']);
  protectedResourceMap.set('http://localhost:5000/api/v1.0/get_workspaces',['api://<application_id_of_webapi>/.default'])

  return {
    interactionType: InteractionType.Popup,
    protectedResourceMap
  };
}

export function MSALGuardConfigFactory(): MsalGuardConfiguration {
  return { 
    interactionType: InteractionType.Popup,
    authRequest: {
      scopes: ['api://<application_id_of_webapi>/.default'],
    },
  };
}

Then I used acquireTokenPopup msal function to get an access token.

And then I call my backend API like this:

this.http.get('http://localhost:5000/api/v1.0/get_workspaces')

My Flask web API:

@app.route('/api/v1.0/get_workspaces', methods=['GET'])
def get():

        current_access_token = request.headers.get("Authorization", None)

        msal_client = msal.ConfidentialClientApplication(
            client_id=app.config['CLIENT_ID'],
            authority=app.config['AUTHORITY'],
            client_credential=app.config['CLIENT_SECRET'])

        # acquire token on behalf of the user that called this API
        arm_resource_access_token = msal_client.acquire_token_on_behalf_of(
            user_assertion=current_access_token.split(' ')[1],
            scopes=app.config['SCOPE']
        )
        print( arm_resource_access_token) /////////////////// ******* I'm getting the error here

        headers = {
            'Authorization': arm_resource_access_token['token_type'] + ' ' + arm_resource_access_token['access_token']}

        workspaces= requests.get(app.config['ENDPOINT'] + 'workspaces', headers = headers).json()
        print(workspaces)
        return jsonify(workspaces)

In my angular console, I'm getting this:

image

In my Flask terminal I'm getting this:

AADSTS65001: The user or administrator has not consented to use the application with ID <webapi_ app_id>.

In Azure portal, I registered both spa and web API:

image

I exposed the API on my backend, and added it in my frontend registration.

And I add my spa app_id on the Authorized client applications.

Kayseri answered 28/5, 2022 at 21:27 Comment(0)
I
21

AADSTS65001: The user or administrator has not consented to use the application

This error usually occurs when you missed granting admin consent to the added scope while retrieving access token.

To resolve the error, please check whether you exposed the API like below:

Go to Azure Portal -> Azure Active Directory -> App Registrations -> Your App -> Expose an API

enter image description here

After exposing the API, make sure to grant API permissions for it like below:

Go to Azure Portal -> Azure Active Directory -> App Registrations -> Your App -> API permissions -> Add a permission -> My APIs -> Your API

enter image description here

  • After adding API permissions, make sure to grant admin consent if it is required.

  • As you are trying to get access token, please check whether you enabled the below options:

Go to Azure Portal -> Azure Active Directory -> App Registrations -> Your App -> Authentication

enter image description here

Please check the below links if error still persists:

azure active directory - InteractionRequiredAuthError: AADSTS65001: The user or administrator has not consented to use the application with ID - Stack Overflow

.net - "AADSTS65001: The user or administrator has not consented to use the application" occurs when token is acquired on behalf of a user - Stack Overflow

UPDATE:

As mentioned by you in the comment, make sure to add your client application to known client applications list

Isoprene answered 29/5, 2022 at 1:22 Comment(4)
thank you @SrideviMachavarapu-MT, but the admin grant is not required and please is it mandatory to enable implicit flows and hybrid flows even if I'm using the authorization code flow to get the token ?Kayseri
If you are using authorization code flow, it is not mandatory to enable those two options. Check this link to know more about On-behalf-of flowIsoprene
I'm still getting the same error, Please I have another question: When the user logs in from spa, do he normally get to consent to the permissions I've added on the web API? because all I get in the consent screen is the exposed scope for example api://<<web-api-id>>/.default is that normal ?Kayseri
If you configure user consent settings as allow user consent for apps or from verified publishers option, they will get consent screen.Isoprene
C
0

There's one other potential gotcha here beyond the Azure Portal: Scope.

In setting up my authentication scheme where a user would login to Microsoft first and then return to my application, I found that the Graph API really likes for the scope part to be

https://graph.microsoft.com/.default

As in the initial URL looks like this (line breaks for clarity)

https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize?response_type=code
&client_id=<client ID>
&redirect_uri=<your URL here>
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&state=<your state here>
&code_challenge=<challenge hash>
&code_challenge_method=S256

I was using https://graph.microsoft.com/user.read and similar specific options for scope. If you do that, and console changes outlined by Sridevi don't fix it, try changing that.

Caudad answered 17/5, 2023 at 20:49 Comment(0)
S
0

My problem was due to misconfigured application environment variables. Calling a downstream API, with improperly configured clientId, clientSecret, and access token scope values caused a blocked request by CORS. Be sure to validate that your deployments are reading in the correct values.

Stinson answered 14/7, 2023 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.