Front Channel API Request Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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