Search code examples
javascriptnode.jsazure-ad-msal

MSAL verify token server-side


We're moving an app from "Sign-In with Google" to "Sign-In with Microsoft". It is an SPA, but queries an API for data. The client-side is all working using MSAL v2 (msal-browser.min.js), and we can sign in and out just fine.

When we send requests to the server, we send the JWT ID token. The server is a NodeJS API.

I can't see any Microsoft server-side Node library that has a 'verify' method we can use to validate the ID token from the client.

We've been looking at @azure/msal-node and @azure/msal-common, but can't see anything that we can feed the ID token to, to verify that the token is valid, and that the user is logged in.

We want to return 'unauthorised' from the API if the user is not logged in.

With Google, this was easy, we used google-auth-library like this:

const client = new OAuth2Client(googleClientId)
const ticket = await client.verifyIdToken({ idToken: googleIdToken, audience: googleClientId })
const payload = ticket.getPayload() // jwt payload

I hope the Microsoft equivalent is just hard to find, or it's not and I'm just being silly in not finding it.

Is there a Node library that provides a way to verify an MSAL ID token, which confirms the token is valid and that the user is signed in...?


Solution

  • MSAL Node is for acquiring tokens so clients can access protected resources, not for validating tokens in your API. I don't think Microsoft currently provides any Node libraries for validating tokens, but you can use jsonwebtoken instead.

    There is a code sample in the MSAL Node library that shows how to validate certain claims in tokens.

    If you are curious what the steps to validate an Azure AD JWT are in more detail, I wrote an article that walks through the various steps. The code sample is written in Java, but all of the steps are applicable to Node as well.