How to secure Web API with passport-azure-ad (/w vue-msal)

Tags: , , ,



I want to secure Web API with passport-azure-ad and use bearerStrategy. I follow the example the module has provided and pass metadata and clientId, I always got 401 unauthorized.

Here is my configs of passport-azure-ad

{

  identityMetadata: 'https://login.microsoftonline.com/<your_tenant_guid>/v2.0/.well-known/openid-configuration'
  
  // Required
  clientID: '<client ID>',

  // Required.
  // If you are using the common endpoint, you should either set `validateIssuer` to false, or provide a value for `issuer`.
  validateIssuer: false,

  // Required. 
  // Set to true if you use `function(req, token, done)` as the verify callback.
  // Set to false if you use `function(req, token)` as the verify callback.
  passReqToCallback: false,

  // Optional. Default value is false.
  // Set to true if you accept access_token whose `aud` claim contains multiple values.
  allowMultiAudiencesInToken: false,

  loggingLevel:'error',
};
}

I provided authorization request header with the access token generated by vue-msal.
I also checked the access token’s signature is not valid as well.

In addition, I used ID token instead but still 401 unauthorized.

In portal /AAD /App registration, I’ve enabled both of implicit grant flowã€accessTokenAcceptedVersion: 2ã€granted admin consent for my subscription in API permissions

What else did I missed ?

Answer

In your case, you could follow this Use passport.authenticate to protect resources or APIs, also make sure you use the correct scope when using vue-msal to get the token.

server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);


Source: stackoverflow