Skip to content

Instantly share code, notes, and snippets.

@petrsvihlik
Created July 18, 2022 09:37
Show Gist options
  • Save petrsvihlik/4de2c06e1823e2b45e5842d9f20b2217 to your computer and use it in GitHub Desktop.
Save petrsvihlik/4de2c06e1823e2b45e5842d9f20b2217 to your computer and use it in GitHub Desktop.
Azure AD & JWKS & PEM & Express.js validation
const getPem = require('rsa-pem-from-mod-exp');
const fetch = require('node-fetch');
const jwt = require('jsonwebtoken');
var keysUri = `https://login.microsoftonline.com/${process.env.AAD_TENANT_ID}/discovery/keys?appid=${process.env.AAD_CLIENT_ID}`;
fetch(keysUri, { redirect: 'manual' }).then(response => response.json())
.then(data => {
var decodedToken = jwt.decode(token, { complete: true });
var key = data.keys.find((_key) => _key.kid === decodedToken.header.kid);
var pem = getPem(key.e, key.n);
const isValid = jwt.verify(token, pem, {/* algorithms: ['RS256']*/ }, function (err, payload) {
console.log(err);
// if token alg != RS256, err == invalid signature
});
if (isValid) {
req.user.oid = decodedToken.oid;
}
});
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
// Express middleware
const verifyToken = function (req, res, next) {
// Verify JWT integrity and check the required scopes
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
function getKey(header, callback) {
var keysUri = `https://login.microsoftonline.com/${process.env.AAD_TENANT_ID}/discovery/keys?appid=${process.env.AAD_CLIENT_ID}`
var client = jwksClient({
jwksUri: keysUri
});
client.getSigningKey(header.kid, function (err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, {}, function (err, user) {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next()
});
} else {
res.sendStatus(401);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment