2

I'm trying to make script to generate my authentication bearer token for collections. so I don't have to pass token each time and I will Inherit auth from parent. But I don't know where I'm wrong in script, I'm not able to generate token and it giving me error

There was an error in evaluating the Pre-request Script:  Error: No data, empty input at 1:1 ^

Here is my script,

var expiresOn = pm.variables.get('ExpiresOn');
    if (!expiresOn || new Date(expiresOn) <= new Date()) {

    var clientId = '565v7677676vfdrd';
    var apiToken =  '6565fdvdrdfd';

    var request = {
        url: 'http://.../auth/token',
        method: 'POST',
        header: 'Content-Type:application/Json',
        body: {
            mode: 'application/json',
            raw:  clientId + apiToken
        }
    };
            }
        };

        pm.sendRequest(request, function (err, res) {
            if (res !== null) {
                var json = res.json();
                pm.environment.set('Access_Token', json.access_token)

                var expiresOn = new Date(0);
                expiresOn.setUTCSeconds(json.expires_on);
                pm.environment.set('ExpiresOn', expiresOn);
            }
        });
    }
nancy
  • 89
  • 1
  • 1
  • 9

3 Answers3

3

const echoPostRequest = {
  url: 'https://example.com/sign_in?client_id=dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
  method: 'POST',
  header: 'Accept: application/json\nUser-Agent: Example/2019.10.31-release (Android 6.0.1; LGE Nexus 5)\nUDID: 1d2c7e65f34b3882f8e42ab8d6a82b4b\nContent-Type: application/json; charset=utf-8\nHost: api-mobile.example.com',
  body: {
    mode: 'application/json',
    raw: JSON.stringify(
        {
         client_id:'dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
         client_secret:'aBK1xbehZvrBw0dtVYNY3BuJJOuDFrYs',
         auth_method:'password',
         create_if_not_found:false,
         credentials:{identifier:'username',password:'pass'},
         signature:'2:a899cdc0'
        })
  }
};

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(echoPostRequest, 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());
        }
    });
}
The above example is a Postman Pre-request script to fetch access_token, and the expire time of the token. I think this example will help you to solve the issue. Please check the console of the postman Open Postman Console by pressing Ctrl+Alt+C on Windows (Cmd + Alt+ C on mac)

enter image description here

Sebin Sunny
  • 1,753
  • 10
  • 9
2

Syntax error

When running your script I got the following error:

There was an error in evaluating the Pre-request Script:  SyntaxError: Unexpected token ';'

It should be something like this in order to run correctly:

    var expiresOn = pm.variables.get('ExpiresOn');
        if (!expiresOn || new Date(expiresOn) <= new Date()) {

        var clientId = '565v7677676vfdrd';
        var apiToken =  '6565fdvdrdfd';

        var request = {
            url: 'https://api.domain.io/api/user/session',
            method: 'POST',
            header: 'Content-Type:application/Json',
            body: {
                mode: 'application/json',
                raw:  clientId + apiToken
            }
        };
                }

            pm.sendRequest(request, function (err, res) {
                if (res !== null) {
                    var json = res.json();
                    pm.environment.set('Access_Token', json.access_token)

                    var expiresOn = new Date(0);
                    expiresOn.setUTCSeconds(json.expires_on);
                    pm.environment.set('ExpiresOn', expiresOn);
                }
            });

Additional options

I used one of these two options to get the bearer token for my collection:

  1. https://gist.github.com/bcnzer/073f0fc0b959928b0ca2b173230c0669#file-postman-pre-request-js
  2. https://community.postman.com/t/how-to-automatically-set-a-bearer-token-for-your-postman-requests/10126/2
Alon Lavian
  • 1,149
  • 13
  • 14
1

A bit modified Sebin Sunny's answer tested with JWT against Azure + resource (/audience).

In headers of request use Authorization {{$randomLoremSentence}}

const echoPostRequest = {
    url: 'https://login.microsoftonline.com/{tenant}/oauth2/token',
    method: 'POST',
    body: {
        mode: 'formdata',
        formdata: [
            { key: 'grant_type', value: 'client_credentials' },
            { key: 'client_Id', value: '*******************************' },
            { key: 'client_secret', value: '*******************************' },
            { key: 'resource', value: '*******************************' }
        ]
    }
};

var getToken = true;

var token = pm.globals.get('$randomLoremSentence') || '';
var exp = pm.globals.get('accessTokenExpiry');
var exps = new Date(exp);
if (token.indexOf('Bearer ') < 0) {
    console.log('Token or expiry date are missing')
} else if (exp <= (new Date()).getTime()) {
    console.log('Token is expired - ${exps}')
} else {
    getToken = false;
    console.log(`Token ${token.substr(0,10)}...${token.substr(-5)} and expiry ${exps} date are all good`);
}

if (getToken === true) {
    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            var responseJson = res.json();
            var token = responseJson.access_token;
            console.log(`Saving the token ${token.substr(0,5)}...${token.substr(-5)} and expiry ${exps} date`)
            pm.globals.set('$randomLoremSentence', "Bearer " + token);
           
            var expiryDate = new Date(responseJson.expires_on * 1000);
            pm.globals.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}
//pm.globals.set('$randomLoremSentence', 0); // reset token 2 test
Jan
  • 2,178
  • 3
  • 14
  • 26