Creating a Encoded JWT (JSON Web Token) Access Signature (Token) using the Postman for authentication as ‘pre-request script’ was a requirement for a specific project I was engaged.
After analyzing the surrounding for couple of hours, was able to successfully sketch the solution to create the token with the dynamical time stamp and the requisites to cater the authentication requirement
AuthToken / JWT = Header + Payload + Signature
(JTW format as an example : xxxxxx.yyyyy.zzzzzz)
Header aka Token Header;
“typ”: “JWT” }
Payload contains the claims which are the statement about the entity and additional meta data. Since the claims are custom claims created to share information between the Private Claims are used out of the three-type of claims. (Claim names are three characters long as JWT is suppose to be compact) — Ref: jwt.io
The custom claims for the payload based on the requirement is as following;
iat — Unix timestamp format
jti — Unique nonce value. (Requests with a repeated jti value will be rejected).
sub — Your API key.
To create requisites for the the Payload;
- iat is generated with;
2. jti is generated with;
3. sub is the API Key.
After creating the payload separately with requisites (iat,jti,sub), the header & the payload should be cast into a base64object and concatenate together with a period (.) in between. Concatenated string is called as the unsignedToken.
Ps: even thought the JWT.io instruction guide is specifying about an encoding mechanism of base64EncodeURL, the Base64 would do the needful from CryptoJS.enc.Base64.stringify();
Example for a signature created using the HMAC-SHA256 algorithm;
Since unsignedToken is the concatenated combination of the base64 encoded header and payload;
base64UrlEncode(header) + “.” + base64UrlEncode(payload)
can be replaced from the unsignedToken metioned below.
Therefore to create the signature in above format the signatureHash should be created first.
Create the HMAC SHA256 aka HS256 algorithm encoded signatureHash with Secret-Key and the unsignedToken created prior as follows;
Once the signatureHash is generated;
the signature encoded with Base64 can be generated from it.
After generating the signature encoded with Base64, the unsigned Token (which is a concatenation of the base64object encoded header and payload) should concatenate with the generated signature while placing a period (‘.’) in between.
As the final step the illegal characters should be removed from the created token.
The formatted token can be used as the JWT-Auth-Token for the authentication;
Once the JWT-Auth-Token is created as the environment-variable within the postman, it can be used for the Authorization header as a param.
Entire code snippet / pre-requisite script written in JS as follows;