Sunday, March 22, 2026

Postman - JS Script to generate JWT assertion

const jsrsasign_code = pm.globals.get("jsrsasign_code");

var navigator = {}; 

var window = {}; 

eval(jsrsasign_code); 


// 2. Format the Private Key (Removes extra spaces/hidden characters)

let rawKey = pm.environment.get("privateKey");

const privateKey = rawKey.replace(/\\n/g, '\n');


// 3. Define Header and Payload

const header = { alg: 'RS256', typ: 'JWT' };

const payload = {

    iss: pm.environment.get("vasuclientId"),

    sub: pm.environment.get("vasuusername"),

    aud: pm.environment.get("loginUrl"),

    exp: Math.floor(Date.now() / 1000) + 900 

};


// 4. Generate the Signed Assertion

const sHeader = JSON.stringify(header);

const sPayload = JSON.stringify(payload); 


// This specific method produces the compact JWT string Salesforce expects

const signedAssertion = KJUR.jws.JWS.sign("RS256", sHeader, sPayload, privateKey);


// 5. CRITICAL: Clean the string for the Body

// Ensures no stray spaces or hidden characters are sent to Salesforce

pm.variables.set("jwt_assertion", signedAssertion.trim());


No comments:

Post a Comment