Create a JWT Token Using a Secure String
The following sample shows how to use a JWT token using https.SecureString. For more information about SecureString, see https.SecureString.
Note:
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
Important:
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
// This script creates a JWT token using https.SecureString.
define(['N/https', 'N/encode'], (https, encode) => {
function onRequest(context) {
let nameToken = "custsecret_myName";
let passwordToken = "custsecret_myPassword";
let headerObj = {
"alg": "HS256",
"typ": "JWT"
}
let payloadObj = {
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239002
}
let headerJSON = JSON.stringify(headerObj);
let payloadJSON = JSON.stringify(payloadObj);
let headerBASE64 = encode.convert({
string: headerJSON,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64_URL_SAFE
});
let payloadBASE64 = encode.convert({
string: payloadJSON,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64_URL_SAFE
});
headerBASE64 = headerBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
payloadBASE64 = payloadBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
let secStringJwtSignature = https .createSecureString({
input: headerBASE64 + "." + payloadBASE64
})
.hmac({
algorithm: https.HashAlg.SHA256,
key: https.createSecretKey({
secret: passwordToken,
encoding: encode.Encoding.UTF_8
}),
resultEncoding: encode.Encoding.BASE_64_URL_SAFE
})
.replaceString({ // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
pattern: "=",
replacement: ""
})
let secStringJwtAuthHeader = https .createSecureString({
input: "Bearer " + headerBASE64 + "." + payloadBASE64 + "."
})
.appendSecureString({
secureString: secStringJwtSignature,
keepEncoding: true
})
// Reflect the response using a echo-request suitelet
let resp = https.get({
url: "myURL",
headers: {
"Authorization": secStringJwtAuthHeader
}
});
{
log.debug("resp-code", resp.code);
log.debug("resp-body", resp.body);
let respAuth = JSON.parse(resp.body)["headers"]["Authorization"];
log.debug("reps-head-auth", respAuth);
log.debug("reps-head-auth-expected",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.uel3RLILSJ9Q9W2Gomh8vAJQAgdbnd6TS4b7plyFOtA" ); // see https://jwt.io/#debugger-io
}
}
return {
onRequest: onRequest
};
});