To validate an Azure B2C token in TypeScript, you can use the jsonwebtoken
library. Here is a function that does this:
- Install the necessary libraries:
npm install jsonwebtoken jwks-rsa axios
- 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:
- Decodes the token to get the header and payload.
- Retrieves the signing key using the
kid
from the token header. - Verifies the token using the
jsonwebtoken
library, checking the issuer and audience.