question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Confirming Bearer Token validity on backend

See original GitHub issue

Core Library

MSAL.js v2 (@azure/msal-browser)

Core Library Version

2.14.1

Wrapper Library

Not Applicable

Wrapper Library Version

None

Description

We are currently using MSAL on our Vue.js front-end and using the returned Access Token as a Bearer Token to authenticate with our Hapi.js Backend server using JWT/JWKs

I am testing moving to MSAL v2 and am successfully (I think) retrieving an Access Token and attatching it to our back-end API calls. I can see the incoming token on the Back-End.

However the request are being rejected as “Invalid Token” errors.

Has the method of authenticating Tokens on the back-end changed from MSAL 1.4 to 2.0?

MSAL Configuration

this.msalConfig = {
      auth: {
        clientId: 'redacted',
        authority: 'redacted',
        redirectUri: process.env.VUE_APP_REDIRECT,
        validateAuthority: true
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: true
      }
    }

this.loginRequest = {
      scopes: ['user.read']
    }

Relevant Code Snippets

Front-end: 
const tokenData = await this.getTokenPopup(this.loginRequest, resp.account)
  const accessToken = tokenData.accessToken
  Vue.prototype.$http.defaults.headers.common.Authorization = `Bearer ${accessToken}`

Backend (jsonwebtoken/jwks-rsa): 
register: async (server) => {
    await server.register(jwt)
    // Confirm that we are getting the correct PK
    const key = jwksRsa.hapiJwt2KeyAsync({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: 'https://login.microsoftonline.com/common/discovery/keys'
    })

    console.log(key)

    server.auth.strategy('jwt', 'jwt', {
      // Get the complete decoded token, because we need info from the header (the kid)
      complete: true,
      // Dynamically provide a signing key based on the kid in the header and the singing keys provided by the JWKS endpoint.
      key: key,
      headerKey: 'authorization',
      tokenType: 'Bearer',
      validate: userCtrl.validate,
      verifyOptions: {
        algorithms: ['RS256'] // or HS256 RS256
      }
    })
    server.auth.default('jwt')
  }

Identity Provider

Azure AD / MSA

Source

External (Customer)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:18 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
derisencommented, Oct 12, 2021

@dankell MSAL itself does not validate tokens, only acquires them (for the moment at least, in future msal-node will have support for this). Or are you suggesting that tokens obtained via MSAL v1 was working, but via MSAL v2 are not?

I assume you are using passport.js on the backend? If so, I would recommend using passport-azure-ad for validating Azure AD / B2C tokens. See an example for this here. A less ideal option would be validating them manually, see an example for this here.

Regardless, for this particular error, we should try to get more detail on why they are deemed invalid. Can you turn on detailed error logs for passport.js?

1reaction
jo-arroyocommented, Oct 27, 2021

@dankell Unfortunately, tokens from Microsoft Graph in particular are not be able to be validated, as they intended for Microsoft Graph only, and should not be opened in any way. Trying to validate it will generate an “Invalid Signature” error. Can you try registering a custom scope, and validating a token with only that scope, instead of user.read?

This thread may be helpful in explaining further.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validate Access Tokens - Auth0
Describes how to validate an access token. ... Identity Provider (IdP) access tokens do not require validation. Pass the IdP access token to...
Read more >
Authenticate with a backend server - Google Developers
To verify that the token is valid, ensure that the following criteria are satisfied: ... Or, if multiple clients access the backend:
Read more >
How to Validate a JWT Access Token - OneLogin Developers
We then check that the token hasn't expired by verifying that the exp claim's value is greater than the current time. Finally, check...
Read more >
Token Validation: What It Is and How to Set It Up - Fusebit
Access tokens are keys that serve as the basis for certifying the authenticity of a user or their privileges within an application. In...
Read more >
Validate Access Tokens - Okta Developer
Retrieve The JSON Web Keys · Decoding and Validating the Access Token · Get the signing keys · Validate a token · Additional...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found