Using Postman Pre-Request Script for JWT authentication
Intro
For the purposes of auth, a JWT is a token that is issued by the server. The token has a JSON payload that contains information specific to the user. This token can be used by clients when talking to APIs (by sending it along as an HTTP header) so that the APIs can identify the user represented by the token, and take user specific action.
- The user logs in with a login API call.
- Server generates JWT Token and
refresh_token
- Server sets a
HttpOnly
cookie withrefresh_token
.jwt_token
andjwt_token_expiry
are returned back to the client as a JSON payload. - The
jwt_token
is stored in memory. - A countdown to a future silent refresh is started based on
jwt_token_expiry
Let’s say our token is only valid for 15 minutes. In this case we’ll probably get an error from our API denying our request (let’s say a 401: Unauthorized
error). Remember that every service that knows how to use a JWT can independently verify it and check whether it has expired or not.
Now if we are testing an API services secured by JWT using Postman, it will be annoying to renew the token each time the token is expired.
Solution
Pre-request scripts are snippets of code associated with a collection request that are executed before the request is sent. This is perfect for refreshing the JWT token. You can set an environment variable in the request header with the value returned from a function.
Using the PM object from Postman sandbox API, pm containing the script that is running, can access variables and has access to a read-only copy of the request or response.
The pm.sendRequest function allows to send simple HTTP(S) GET requests from tests and pre-request scripts.
In our case, pm.sendRequest will be used to renew the JWT token before the request is sent.
Supposing the responing will be a JSON with property token containing the renewed JWT token.
pm.environment.set will store the renewed token in the Auth variable.
Conclusion
We saw in this short article how we can renew the JWT token and store it automatically in the header of a secured request before sending it using Pre-request script in Postman.