Search code examples
azureazure-active-directoryazure-ad-graph-apiazure-ad-msalazure-authentication

I got a token from AAD using Msal, but can't get the user profile using the token acquired. How to validate the token simply on Node backend?


I used the following configuration for requesting the token from AAD.

The app.module.ts file:

MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }

It returns the msal.idtoken, accesstoken, and some more msal key value pairs. Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.


Solution

  • I see that you have the right config on the Portal.

    If you are using MSAL.js, given some code like this:

        this.app = new Msal.UserAgentApplication(
    
            this.applicationConfig.clientID,
    
            `https://login.microsoftonline.com/${AzureADName}/`,
    
            () => {
    
                // callback for login redirect
    
            },
    
            {
    
                redirectUri
    
            }
    
        );
    

    You would then call this to get user information:

    this.app.getUser();
    

    or

    this.app.getAccount();
    

    You would have to provide version information to be sure, as the API was changed.