Postman API Authentication with Pre-request Script
Postman (https://www.postman.com/) is a popular client for working with REST API and includes many useful tools to make our life easier. A common authentication method for such APIs is a Bearer Token scheme where we pass a token received from the authentication server in an “Authorization” HTTP header. Unfortunately, the token is usually short-lived, so we need to refresh it from time to time. Postman makes it easy to refresh the token automatically behind the scenes before sending a request. We will use environment variables and a powerful pre-request script to ensure our credentials are always valid.
In my case, I am using Keycloak (https://www.keycloak.org/) for issuing OAuth2/OpenID tokens with a password grant type for convenience, but you can apply a similar approach to other auth servers and credential grant types.
Environment variables
Environment variables are a way to store and share the data between the API requests. I am defining the following ones:
- sso_url — HTTP address of Keycloak token endpoint like https://<KEYCLOAK_HOST>/auth/realms/<REALM_NAME>/protocol/openid-connect/token
- sso_username — username for password grant
- sso_password — password for password grant
- token — variable to store current token
- token_expires_at — variable to store the token expiration date
Global Collection Authorization
Postman lets you group requests into collections and set a common authentication type for all of them. Our token is stored inside the “token” environment variable and we use the Bearer type so the Authorization settings should look like that:
It means that for every request in the Collection, Postman will add HTTP header “Authorization: Bearer {{token}}”.
Global Collection Pre-request Script
In the same Collection where we defined Authorization, we can also add a pre-request script that executes before each request. Here we do the actual token validation and refresh it whenever needed.
Now, everytime we send a request inside the Collection the pre-request script will check the token and refresh it when needed. The valid token is always stored in the “token” variable so Authorization settings fill the Authorization header with a valid credentials.
Do you know any other useful use case for pre-request scripts? Share it in a comment!