Search code examples
javascriptnode.jsopenid-connectpassport-azure-ad

passport-azure-ad unable to validate `id_token` due to wrong KID


I'm encountering an issue when using the passport-azure-ad library where the library throws an error when trying to validate the id_token. The specific error message is "authentication failed due to: In _validateResponse: failed to generate PEM key due to: a key with kid %s cannot be found"

I can see that the kid in the id_token's header is a value which does not appear in the keys discovery endpoint (of the format https://login.microsoftonline.com/{tenantId}/discovery/v2.0/keys).

Is there any reason why this might happen? I'm unable to figure it out.

My code is the following:

passport.use(
  new OIDCStrategy({
    clientID: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    identityMetadata: IDENTITY_METADATA_URL,
    redirectUrl: SUCCESS_REDIRECT_URI,
    responseMode: 'form_post',
    responseType: 'code',
    scope: 'email profile',

    loggingLevel: 'info',
    loggingNoPII: false
  })
)

app.get(
  '/oauthv2/login',
  passport.authenticate(
    'azuread-openidconnect',
    { failureRedirect: '/fail' },
    (req, res) => {
      // ...
    }
  )
)

app.post(
  '/oauthv2/success',
  passport.authenticate(
    'azuread-openidconnect',
    { failureRedirect: '/' },
    (req, res) => {
      // ...
    }
  )
)

From the pazzport-azure-ad logs I can see the following steps are carried out before the error occurs:

  • received id_token
  • received access_token
  • received refresh_token
  • token decoded
  • working on key
  • working on key
  • working on key
  • authentication failed due to: In _validateResponse: failed to generate PEM key due to: a key with kid %s cannot be found

Solution

  • So, it turns out that I had created a v1 App in Azure Active Directory, although this was not clear ANYWHERE and the id_token said it was ver: 2.0 but it wasn't....

    If you want a v2.0 app in Azure AD you cannot create it from the Enterprise Applications section, you have to use the App registrations (Preview) section.

    This solved my issue and the id_token contained a valid KID after I deleted my app and recreated it correctly.

    Hope this helps anyone who encounters the same problem!

    Useful link: https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

    If anyone from Azure reads this, please know that adding (Preview) in the title of any section means that I will automatically not click it because it seems like it's not something important. However, in this case it was the ONLY way to create a v2.0 app!