Eric Cai
Eric Cai

Reputation: 83

How to get Azure access token using client secret in MSAL?

I have been trying to migrate a web app from Flask to react, and I had trouble getting a valid access token. In Flask, I used adal and had following codes:

authority_host_uri = 'https://login.microsoftonline.com'
tenant = '<my tenant id>'
authority_uri = authority_host_uri + '/' + tenant
resource_uri = 'https://management.core.windows.net/'
client_id = '<my client id>'
client_secret = '<my client secret>'
context = adal.AuthenticationContext(authority_uri, api_version=None)
mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)

and the response was

{'tokenType': 'Bearer',
 'expiresIn': 3599,
 'expiresOn': '2020-05-27 18:22:07.128189',
 'resource': 'https://management.core.windows.net/',
 'accessToken':'<the access token that was needed>'
 'isMRRT': True,
 '_clientId': '<client id info>',
 '_authority': '<authority above>'}

However, while I was trying to implement the same thing in msal in React, the access token that I got from

const tokenRequest = {
    scopes: [clientId + "/user_impersonation"]
};    
const response = await myMSALObj.acquireTokenSilent(tokenRequest)

was not valid, like it will get a 403 error from Azure catalog API, as the access token I got from Flask worked just fine. Are there different types of access token or is it because of the scoping? Is it possible to do the exact same thing as adal did in Flask (like no need to specify the scope, just using client secret to get the right access key? )

Upvotes: 0

Views: 15854

Answers (1)

Carl Zhao
Carl Zhao

Reputation: 9511

The scope is not correct. As you want to access this resource https://management.core.windows.net/

The scope should be:

scopes: ["https://management.core.windows.net/.default"]

Reference:

https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-v1-app-scopes#scopes-to-request-access-to-all-the-permissions-of-a-v10-application

This is due to insufficient permissions, and you grant the administrator consent in accordance with the following procedure:

enter image description here

enter image description here

You can also obtain administrator consent through browser interaction:

https://login.microsoftonline.com/{tenant}/adminconsent?client_id={your-client_id}&state=12345&redirect_uri={your-redirect_uri}

enter image description here

Upvotes: 2

Related Questions