Skip to content

Instantly share code, notes, and snippets.

@mamund

mamund/setAuth0JWT.js

Last active May 5, 2021
Embed
What would you like to do?
auth0 JWT in Postman API Testing
/************************************************
Retrieve a JWT from Auth0 for Postman
2020-05-15 : @mamund @greatwebapis
NOTES:
1) create API definition in Auth0 with
"client_credential" (machine-to-machine)
2) pull the following from Auth0 API config:
- domain
- client_id
- client_secret
- audience
3) set environment vars in Postman with
the Auth0 values
4) add the code below to your collection's
Pre-request Scripts page in Postman.
5) in any request that needs a value JWT
- add "authorization" header with an
{{authorization}} value placeholder
- call this function any time you
need a new JWT.
*************************************************/
function setAuth0JWT() {
// fill local vars from Postman environment
var domain = pm.environment.get("domain");
var client_id = pm.environment.get("client_id");
var client_secret = pm.environment.get("client_secret");
var audience = pm.environment.get("audience");
// load request object
var req = {
url: "https://" + domain + "/oauth/token",
method: "POST",
header: {
"accept": "application/json",
"content-type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(
{
client_id: client_id,
client_secret: client_secret,
audience: audience,
grant_type: "client_credentials"
}
)
}
};
// execute request for JWT, store token, set header
pm.sendRequest(req, function (err, res) {
pm.environment.set("authorization", "Bearer " + res.json().access_token);
pm.request.headers.add(
{
key: "authorization",
value: pm.environment.get("authorization")
}
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment