Skip to content

Instantly share code, notes, and snippets.

@hdornier

hdornier/gist.js Secret

Created April 2, 2021 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hdornier/99d8d90de60a4e1b49e701e32dffefd6 to your computer and use it in GitHub Desktop.
Save hdornier/99d8d90de60a4e1b49e701e32dffefd6 to your computer and use it in GitHub Desktop.
Front Channel API Request Authentication
// Sets the Bearer token to authenticate the request to Front
// In practice, there are libraries that handle JWT creation, but we cannot import them to Postman
// https://jwt.io/#libraries
setToken();
/*
* Given a secret key, generates the API key needed to authenticate the request
*
*/
function setToken() {
const hasAllCredentials = pm.environment.get("secretKey") && pm.environment.get("channelTypeId") && pm.environment.get("channelId");
if (!hasAllCredentials)
throw new Error('Missing environment variable');
const signature = pm.environment.get("secretKey");
const issuer = pm.environment.get("channelTypeId");
const exp = Math.floor(new Date().valueOf() / 1000) + 5; // Current Date + 5 seconds
const payload = {
iss: parseInt(issuer, 10),
jti: randomString(),
sub: pm.environment.get("channelId"),
exp
};
const generatedToken = createJWT(payload, signature);
console.log(generatedToken);
pm.environment.set("generatedToken", generatedToken);
}
// https://www.jonathan-petitcolas.com/2014/11/27/creating-json-web-token-in-javascript.html
// Creates a JSON web token
function createJWT(payload, signature) {
const unsignedToken = createUnsignedToken(payload);
return signToken(unsignedToken, signature);
}
function createUnsignedToken(payload) {
const header = {
"typ": "JWT",
"alg": "HS256"
};
const stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
const encodedHeader = base64url(stringifiedHeader);
const stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(payload));
const encodedData = base64url(stringifiedData);
return `${encodedHeader}.${encodedData}`;
}
// Signs an unsigned token
function signToken(unsignedToken, secret) {
let signature = CryptoJS.HmacSHA256(unsignedToken, secret);
signature = base64url(signature);
return `${unsignedToken}.${signature}`;
}
function base64url(source) {
// Encode in classical base64
encodedSource = CryptoJS.enc.Base64.stringify(source);
// Remove padding equal characters
encodedSource = encodedSource.replace(/=+$/, '');
// Replace characters according to base64url specifications
encodedSource = encodedSource.replace(/\+/g, '-');
encodedSource = encodedSource.replace(/\//g, '_');
return encodedSource;
}
function randomString(n = 16) {
return Math.random().toString(36).slice(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment