Skip to content

Instantly share code, notes, and snippets.

@SumanaMalkapuram
Last active December 18, 2020 18:37
Show Gist options
  • Save SumanaMalkapuram/4a886bfc6f29e9ff8958e381e170b480 to your computer and use it in GitHub Desktop.
Save SumanaMalkapuram/4a886bfc6f29e9ff8958e381e170b480 to your computer and use it in GitHub Desktop.
module.exports = function(client, scope, audience, context, cb) {
const _ = require('lodash');
let access_token = {};
let requested_scopes = context.body.scope;
let jwt = require('jsonwebtoken');
requested_scopes = (requested_scopes && requested_scopes.split(" ")) || [];
access_token.scope = _.intersection(requested_scopes, scope);
if (!context.body.identifier_token) {
return cb('No user identifier');
}
const jwksClient = require('jwks-rsa');
let clientKey = jwksClient({
jwksUri: 'https://<<your_tenant>>.auth0.com/.well-known/jwks.json'
});
function getKey(kid, callback) {
clientKey.getSigningKey(kid, function(err, key) {
if (err) {
return callback(err, null);
}
const signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
function verify(id_token, signingKey, callback) {
jwt.verify(context.body.identifier_token, signingKey, {
algorithms: ['RS256'], audience: context.id, issuer: 'https://<<your_tenant>>.auth0.com/'
}, callback);
}
try {
if (audience === 'https://<<your_tenant>>.auth0.com/api/v2/') { // your tenant's Management API
console.log("id token", context.body.identifier_token);
let idtoken = jwt.decode(context.body.identifier_token, {
complete: true
});
const kid = idtoken.header.kid;
getKey(kid, (err, signingKey) => {
if (err) {
return cb("Failed to get key");
}
verify(context.body.identifier_token, signingKey, (error, decoded) => {
if (error) {
return cb('user Identifier token Failed Validation.');
}
let namespace = 'http://management-api/';
console.log("decoded token", decoded.sub); // you can check if the user is authorized to get the m2m token
access_token[namespace + 'delegateduser'] = decoded.sub; // if the returned M2M access_token requires user details for auditing.
/* Remove all the console logs */
console.log("new access token", access_token);
console.log("user's id_token", context.body.identifier_token);
console.log("requested scope", context.body.scope);
console.log("all scopes agains API", scope);
console.log("intersection of scopes added in access_token", access_token.scope);
cb(null, access_token);
})
});
} else {
cb(null, access_token);
}
} catch (error) {
cb(error, null);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment