0

I am new to using postman to test api. I am trying to fetch a JWT token which I can save as an environment variable in postman. I was referring to this excellent post on how to do it: jwt-postman

I have the below python code which I used before in order to fetch the jwt token.

import requests
from requests.auth import HTTPBasicAuth
import json
session=requests.Session()
client_id ="abcdef"
secret="ghijklmnop"
token_auth="https://TEST/token"
hed = {'Content-Type': 'application/x-www-form-urlencoded'}
response = session.post(token_auth,headers =hed ,data = 'grant_type=client_credentials',auth =  HTTPBasicAuth(client_id,secret),verify = True)
token =  json.loads(response.content)['access_token']
print(token)

How do I write the same functionality in pm.sendRequest ?

Naxi
  • 1,504
  • 5
  • 33
  • 72
  • What part of using the script and filling in the details from that python request are you having issue with? This is the part you might need to use https://gist.github.com/bcnzer/073f0fc0b959928b0ca2b173230c0669#gistcomment-2835535 – Danny Dainton Aug 15 '20 at 22:14

1 Answers1

0

I've not been able to run this but you're going to need to do something like this:

const options = {
    url: 'https://TEST/token',
    method: 'POST',
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: "client_id", value: "abcdef" },
            { key: "client_secret", value: "ghijklmnop" },
            { key: "grant_type", value: "client_credentials" },
        ]
    }
};

var getToken = true;

if (!pm.environment.get('accessTokenExpiry') ||
    !pm.environment.get('currentAccessToken')) {
    console.log('Token or expiry date are missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
    console.log('Token is expired')
} else {
    getToken = false;
    console.log('Token and expiry date are all good');
}

if (getToken === true) {
    pm.sendRequest(options, function (err, res) {
        console.log(err ? err : res.json());
        if (err === null) {
            console.log('Saving the token and expiry date')
            var responseJson = res.json();
            pm.environment.set('currentAccessToken', responseJson.access_token)

            var expiryDate = new Date();
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
            pm.environment.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}
Danny Dainton
  • 23,069
  • 6
  • 67
  • 80