OAuth2 Token into Body

Hi, I am using the “Oauth 2” - “Get New Access Token” functionality, where the token will be auto-filled into the “Access Token” field and then it allows me to “Add authorization data to Request URL or Request Headers”

My problem is: My API needs me to pass the token as an entry in the BODY (specifically, a key called token as x-www-form-urlencoded) - is there any way I can get the token to be placed in the body?

Hi @grehkemper!

Welcome to the community! :clap:

In regards to your issue, what I would suggest in this instance is to obtain the authorization token via a pre-request script, and then saving that token as an environment variable, such as {{authToken}}.

Then using that in your form-urlencoded payload to your service, by just adding the key value pair (token / {{authToken}}.

Not sure how you need to format your request to obtain your token, but if it follows the OAuth 2.0 spec, something like so should work:

  url:  pm.variables.get("Auth_Url"), 
  method: 'POST',
  header: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': pm.variables.get("Basic_Auth")
  body: {
      mode: 'urlencoded',
      urlencoded: [
        {key: "grant_type", value: "password", disabled: false},
        {key: "username", value: pm.environment.get("OAUTH_USERNAME"), disabled: false},
        {key: "password", value: pm.environment.get("OAUTH_PASSWORD"), disabled: false}
  }, function (err, res) {
    pm.environment.set("authToken", res.json().access_token);
    pm.environment.set("OAuth_Timestamp", new Date());
    // Set the ExpiresInTime variable to the time given in the response if it exists
        expiresInTime = res.json().expires_in * 1000;
    pm.environment.set("ExpiresInTime", expiresInTime);

Filling in the correct key value pairs above

*Obtained from: https://medium.com/@allen.helton/how-to-automate-oauth2-token-renewal-in-postman-864420d381a0


Hope this helps!


1 Like

@odanylewycz thanks a lot for the response. I did find a solution based on the example and some of the links your provided. It’s a super-simple one-line pre-request script:

pm.variables.set('mytoken', pm.request.auth.oauth2.get('accessToken'));

… and then i use use {{mytoken}} in the body where i need it.


1 Like

Hi @grehkemper!

Wow thats sweet! I actually had no clue those methods were available through the pm class in postman’s node js module!

I learned something new. Thanks for teaching me :slight_smile:.