Here is JS pattern which will cache the key used for token validation in runtime.
/*
declaring key into variable ahead allows us to write and cache it.
Next time this function runs it sees, that key is not undefined, and just returns the existing object
*/
var processedKey
async function getKey (kid) {
if (!processedKey) {
response = await axiosClient({url:process.env['jwks_uri']}).catch((error) => {
return Promise.reject(error)
})
let keymatch = response.data?.keys.find((key) => {
console.log(key.kid,'looking for',kid)
return key.kid === kid
})
processedKey = '-----BEGIN CERTIFICATE-----' +'\n' + keymatch.x5c + '\n' + '-----END CERTIFICATE-----'
if (!keymatch) {return Promise.reject('no matching key')}
}
return processedKey
}
module.exports = {
jwtverify,getKey
}
The next time getKey runs the function will return the cached variable

0 comments on “Node.js – Azure AD JWT verification key runtime caching”