Passport-azure-ad MSAL Using BearerStrategy gives error

186 views Asked by At

Client(React Js) - @azure/msal-react, @azure/msal-browser Server(Express Js) - Passport-azure-ad

var options = {
    identityMetadata:"https://login.microsoftonline.com/<tennant-id>/v2.0/.well-known/openid-configuration",
    clientID:"<client-id>",
    validateIssuer:true,
    issuer: "https://login.microsoftonline.com/<tennant-id>/v2.0",
    passReqToCallback: false,
    allowMultiAudiencesInToken: false,
    audience:"<client-id>",
    loggingLevel: "info",
    loggingNoPII: false,
    scope: ["User.Read"],
  };

  var bearerStrategy = new BearerStrategy(options,
    function(token, done) {
      log.info('verifying the user');
      log.info(token, 'was the token retreived');
      findById(token.oid, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          log.info('User was added automatically as they were new. Their oid is: ', token.oid);
          users.push(token);
          owner = token.oid;
          return done(null, token);
        }
        owner = token.oid;
        return done(null, user, token);
      });
    }
  );

Error log - {"name":"AzureAD: Bearer Strategy","hostname":"xxxxx-xxxxx","pid":xxxxx,"level":x,"msg":"authentication failed due to: invalid signature","time":"xxxx","v":0}

Though the server receives the accessToken from the client in Headers as Authorization Bearer Token to which it parses and also decodes the token to provide the userInfo. But after generating the pemKey I get the above error log.

What could be the reason for this error log.

Any help is appreciated, thanks

1

There are 1 answers

0
Rukmini On

I created an Azure AD Application and granted API permissions like below:

enter image description here

Generated the access token via Postman using below parameters:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
scope:user.read
grant_type:authorization_code
redirect_uri:https://jwt.ms
code:code
client_secret:ClientSecret

enter image description here

When I decoded the access token, I got the same error as below:

enter image description here

Note that: Tokens generated for Microsoft Graph API shouldn't be validated as it is not meant for the application. Only Microsoft Graph can validate tokens issued for MS Graph itself as suggested by Sérgio Correia.

Only the access token generated for your application can be validated.

Hence, to resolve the error you can Expose an API like below:

enter image description here

Added the API permissions:

enter image description here

I generated access token by passing scope as api://ClientID/test.read

enter image description here

Now the Signature Verified successfully like below:

enter image description here