Get OAuth access token value in Postman

September 16th 2022 Postman

You may not be a fan of Postman, but it is probably the most feature-rich REST client and more.

Need to invoke a REST API with OAuth authentication? You can easily configure the authentication parameters for a folder and get a token by logging in through the identity provider's web interface:

OAuth authentication configuration in Postman

All requests within that folder will then automatically use that token in their Authorization header, unless you configure them otherwise.

For most scenarios, this is sufficient. But what if you need to use this token in a different way? For example, to access UMA (user-managed access) protected resources in Keycloak. A client attempting to access such a resource with the access token will receive a permission ticket that it can use to obtain a RPT ( Requesting Party Token). This RPT must then be used to access the resource.

To allow two different tokens to be used in the Authorization header of the same request, they can be stored in a Postman variable. This should first be set to the value of the access token and then replaced with RPT after it is received.

The crucial question is: How can the access token be put into a Postman variable? Normally, responses to requests can be processed with test code, but that is not the case with authorization requests. After searching for a while, I came across a random comment in a GitHub issue with a suggestion that worked for me:

  • Create a dummy request to an endpoint that uses the access token received.
  • As a test for this request (which is executed afterwards), add code that reads the access token from the request header:

    auth_token = pm.request.getHeaders()["Authorization"];
    auth_token = auth_token.replace("Bearer ", "");
    postman.setEnvironmentVariable("accessToken", auth_token);
    

This code puts the access token value used for the request into the accessToken Postman environment variable. This variable can be used in the Authorization header of all other requests. When a request accesses a UMA-protected resource, the value of the accessToken variable can be replaced with the obtained RPT so that it is used for all future requests.

Postman is a highly configurable and scriptable REST client. However, there are still scenarios that can be difficult to implement. In this post, I described how an OAuth access token retrieved by Postman can be stored in a variable so that the value can be used in places other than the request's Authorization header and also replaced with a different value as is needed to implement calls to UMA-protected resources in Keycloak.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License