I am trying to use jsonwebtoken NPM package for verifying a JWT token issued by Azure Active Directory. Following is the node.js code that I have written:
var jwt = require('jsonwebtoken');
var token = '<valid JWT token>';
var x5cString = '<x5cSTring>';
var publicKey = '-----BEGIN CERTIFICATE-----\n' + x5cString + '\n-----END CERTIFICATE-----';
var verifiedToken = jwt.verify(token, publicKey) //, verifyOptions);
Please note that in the above code I use the actual x5c String from https://login.microsoftonline.com/common/discovery/keys. This works fine and I get the expected result. But, the X5C string which is the public key keeps changing. I am trying to understand how to get this public key automatically.
EDIT
I found some sample code on Jsonwebtoken NPM package web site. In this code signingKey is what I want. Following is the code.
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://login.microsoftonline.com/common/discovery/keys'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});
In the above code, jwt.verify calls getKey that takes header and callback as parameter. I do not understand how jwt.verify function passed 'header' parameter to the getKey. Following is the header that I have retrieved. how do I pass this header to getKey in the jwt.verify?
var decoded = jwt.decode(token, {complete: true});
var header = decoded.header