Skip to content

Instantly share code, notes, and snippets.

@djedi
Last active June 4, 2024 17:27
Show Gist options
  • Save djedi/e8f2ce1a7c530abb063391ca1a4cedae to your computer and use it in GitHub Desktop.
Save djedi/e8f2ce1a7c530abb063391ca1a4cedae to your computer and use it in GitHub Desktop.
Validate Azure B2C token.md

To validate an Azure B2C token in TypeScript, you can use the jsonwebtoken library. Here is a function that does this:

  1. Install the necessary libraries:
npm install jsonwebtoken jwks-rsa axios
  1. Write the function:
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
import axios from 'axios';

const client = jwksClient({
  jwksUri: 'https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/discovery/v2.0/keys'
});

function getKey(header: any, callback: any) {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) {
      callback(err, null);
    } else {
      const signingKey = key.getPublicKey();
      callback(null, signingKey);
    }
  });
}

async function validateToken(token: string): Promise<void> {
  const decodedToken = jwt.decode(token, { complete: true });
  if (!decodedToken || typeof decodedToken === 'string') {
    throw new Error('Invalid token');
  }

  const { header, payload } = decodedToken;
  const issuer = `https://your-tenant-name.b2clogin.com/${payload.tid}/v2.0/`;

  // Verify the token
  return new Promise((resolve, reject) => {
    jwt.verify(token, getKey, {
      algorithms: ['RS256'],
      issuer,
      audience: 'your-api-identifier'
    }, (err, decoded) => {
      if (err) {
        reject(err);
      } else {
        resolve(decoded);
      }
    });
  });
}

// Usage
const token = 'your-jwt-token-here';

validateToken(token)
  .then(() => {
    console.log('Token is valid');
  })
  .catch((error) => {
    console.error('Token validation failed:', error);
  });

Make sure to replace:

  • your-tenant-name with your Azure AD B2C tenant name.
  • your-api-identifier with your API's identifier (the audience for the token).

This function:

  1. Decodes the token to get the header and payload.
  2. Retrieves the signing key using the kid from the token header.
  3. Verifies the token using the jsonwebtoken library, checking the issuer and audience.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment