Getting invalid signature when generating a JWT token

I’m trying to use the following pre-request script, everything works but I’m getting invalid signature, because my secret is already base64 encoded.

How do I set that in the script so it creates the signature correctly ( like the checkbox “secret base64 encoded” on the jwt.io page?

// JWT generation script adapted from

//var jwtSecret = pm.environment.get('jwt_secret') || ''
var jwtSecret = pm.collectionVariables.get('jwt_secret') || ''

console.log("Jwt secret:", jwtSecret)

// Set headers for JWT
var header = {
	'typ': 'JWT',
	'alg': 'HS256'
};

// Prepare timestamp in seconds
var currentTimestamp = Math.floor(Date.now() / 1000)

var data = {
	'iss': pm.collectionVariables.get('jwt_iss') || '',
	'iat': currentTimestamp,
	'exp': currentTimestamp + 300, // expiry time is 30 seconds from time of creation
}


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
}

// 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, jwtSecret)

signature = base64url(signature)

var signedToken = `${token}.${signature}`


pm.environment.set('jwt_signed', signedToken)
console.log('Signed and encoded JWT', signedToken)

I fixed it. I had to decode the secret before adding it to the signature.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.