Last active
December 22, 2020 09:35
-
-
Save tooooolong/2ee9a0eb5f07f3339f16718619a53d30 to your computer and use it in GitHub Desktop.
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
// This code is a script used in Postman | |
// It can generate auth token for BigONE OpenAPI | |
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 addIAT(request) { | |
var iat = Math.floor(Date.now() / 1000) + 257; | |
data.iat = iat; | |
return data; | |
} | |
var header = { | |
"typ": "JWT", | |
"alg": "HS256" | |
}; | |
// var nonce = (Date.now() * Math.pow(10, 6)).toString(); | |
var nonce = (Date.now() * Math.pow(10, 6)); | |
var data = { | |
"sub": pm.variables.get("api_key"), | |
"type": "OpenAPIV2", | |
"nonce": nonce, | |
"recv_window": "10", | |
}; | |
// data = addIAT(data); | |
var secret = pm.variables.get("api_secret"); | |
// encode header | |
var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header)); | |
var encodedHeader = base64url(stringifiedHeader); | |
// encode data | |
var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data)); | |
var encodedData = base64url(stringifiedData); | |
// build token | |
var token = encodedHeader + "." + encodedData; | |
// sign token | |
var signature = CryptoJS.HmacSHA256(token, secret); | |
signature = base64url(signature); | |
var signedToken = token + "." + signature; | |
// You should use `jwt_sign` variable in your header | |
postman.setEnvironmentVariable("jwt_sign", signedToken); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment