Created
July 18, 2022 09:37
-
-
Save petrsvihlik/4de2c06e1823e2b45e5842d9f20b2217 to your computer and use it in GitHub Desktop.
Azure AD & JWKS & PEM & Express.js validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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