Script for obtaining authorization bearer token in Postman before sending request

I am currently working on a script to automate the generation of my authentication bearer token for collections. This way, I won't have to manually pass the token each time and can inherit authentication from the parent. However, I seem to be encountering an issue with the script as it is not successfully generating the token and is throwing an error.

An error occurred while evaluating the Pre-request Script: Error: No data, empty input at 1:1 ^

Below is the script in question:

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: 'raw',
            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);
            }
        });
    }

Answer №1

const fetchAccessToken = {
  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 shouldFetchToken = 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 {
    shouldFetchToken = false;
    console.log('Token and expiry date are all good');
}

if (shouldFetchToken === true) {
    pm.sendRequest(fetchAccessToken, 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 demonstrates how to fetch an access token and its expiration time using a Postman pre-request script. This example can help you resolve similar issues. Make sure to monitor the Postman Console for any feedback. Access the Postman Console by pressing Ctrl+Alt+C on Windows or Cmd+Alt+C on Mac.

https://i.sstatic.net/9fdZA.png

Answer №2

Syntax problem

After executing your code, I encountered the following issue:

An error occurred while evaluating the Pre-request Script:  SyntaxError: Unexpected token '('

To resolve this and ensure proper execution, consider revising the script as shown below:

    var sessionExpires = pm.variables.get('SessionExpires');
        if (sessionExpires && new Date(sessionExpires) <= new Date()) {

        var clientID = 'abc1234';
        var apiKey =  'def5678';

        var requestObject = {
            url: 'https://api.example.com/user/session',
            method: 'POST',
            header: 'Content-Type:application/Json',
            body: {
                mode: 'application/json',
                raw:  clientID + apiKey
            }
        };
                }

            pm.sendRequest(requestObject, function (error, response) {
                if (response !== null) {
                    var jsonData = response.json();
                    pm.environment.set('Access_Token', jsonData.access_token)

                    var sessionExpires = new Date(0);
                    sessionExpires.setUTCSeconds(jsonData.expires_on);
                    pm.environment.set('SessionExpires', sessionExpires);
                }
            });

Additional suggestions

I found some useful options that may help you in obtaining the bearer token for your collection:

  1. https://example.com/code-snippet1
  2. https://example.com/code-snippet2

Answer №3

A revised version of Sebin Sunny's solution evaluated using JWT against Azure with the specified resource (/audience).

Include the Authorization header in the request with a randomly generated authorization token.

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

Answer №4

While on a different search mission, I stumbled upon this query.

This particular pre-request script is designed to handle token expiration and includes various tests for troubleshooting convenience in case of any issues.

To make it work correctly, you need to adjust the body according to the appropriate grant type.

let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Checking Environment Variables Before Request", function () {
        let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.environment.get("clientId"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "username", value: pm.environment.get("username"), disabled: false },
                    { key: "password", value: pm.environment.get("password"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Status Code After Microsoft login - 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    pm.environment.set("bearerToken", resJson.id_token);
                    pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

Troubleshooting: HighCharts xAxis not displaying dates correctly when using JSON data

/* Analyzing Historical Performance */ document.addEventListener('DOMContentLoaded', function() { const lineChartUrl = 'https://bfc-dashboard-api.herokuapp.com/line_chart'; Highcharts.getJSON(lineChartUrl, function(data) { va ...

Ways to duplicate or replicate a mongodb collection using a javascript command instead of the command prompt

Recently, I discovered a way to clone a MongoDB collection using a command in the command prompt. Now, I'm interested in creating a script using JavaScript that will run via a cron job in a Node.js environment. In my app.js file, I include the follow ...

Addressing the issue of compatibility with iPhone 5 and 5S in both portrait and landscape modes

I made an attempt to conceal certain elements specifically on iPhone 5 & 5S in both portrait and landscape orientations, but unfortunately, it ended up affecting all iPhone devices. Below is the code snippet used: @media only screen and (min-device ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

Is it feasible to create a comprehensive CRUD application without utilizing a database?

As I utilize a JSON file from my GitHub repository as a mock backend, I have mastered fetching and reading all the information. Is there a way to modify or add new data to this JSON file? Could opting for an alternate mock backend such as Mocky.io provid ...

The seamless flow of web design

Seeking guidance on creating a responsive web page. I have a functional website that looks great on my 13" MacBook, but encounters distortion at different screen sizes. What steps are necessary to ensure it appears crisp and appealing on any device? Should ...

What are the steps to resolve a peer dependency problem with npm?

I am facing a conflict in my package.json file with the following modules: react-router requires react 0.13.x redbox-react requires react@>=0.13.2 || ^0.14.0-rc1 After running npm install react, I ended up with version <a href="/cdn-cgi/l/emai ...

TS7006: Argument 'duplicate' is assumed to have an 'any' data type

I am working on a function that will create a button to copy the content of a variable into the clipboard using TypeScript. Below is my attempted code: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async copyMe => ...

Granting Access to an S3 Object (Specific HTML Page) Using AWS Cognito JS

On my website hosted on s3, I have three HTML files - register.html, login.html, and dashboard.html. After successfully registering and logging in, I obtain an access token. What is the best way to limit access to the dashboard.html file and utilize the ...

Unraveling the Closure Problem in AngularJS

I have been working on a simple todo app using angularjs. The issue I am facing is that only the last value of the array items gets added to the list in the li's. To demonstrate this problem, I have created a sample on jsbin. http://jsbin.com/simafu ...

What is the best way to retrieve JSON data in ReactJS through ExpressJS?

Exploring the realms of reactjs and expressjs, I am seeking guidance on how to extract data from reactjs and store it in a variable. My current achievement includes successfully executing res.send to display the data. app.get('*', (req, res) =& ...

Guide for deploying a Svelte front-end and a Node back-end on Heroku

I have developed a test app using Svelte and now I am looking to deploy it live on Heroku. However, I am facing issues in serving it up properly on Heroku. As someone new to testing and experimenting with these technologies on my own, I tried configuring t ...

Obtain a collection of information from a web API by utilizing jQuery

Click on the following link to access live data from a web API: This is my first attempt at retrieving data from an API, so I may have missed some settings. To test the connection with the API, I included the following code in the HTML page: <div id= ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...

How to beautifully display the hierarchy of nested SASS Maps?

In the realm of SASS programming, particularly within an Angular Theme framework, when dealing with nested maps it is possible to use @debug to log their contents. However, this method currently outputs the information on a single line. Is there a feature ...

What is the preferred method for accessing nested object properties in React props?

Building upon a previous inquiry - Javascript - How do I access properties of objects nested within other Objects It appears that standard dot notation doesn't suffice for accessing nested object properties within React state/props. In the case of t ...

Transferring data from JavaScript to PHP using the $.ajax method for storing information in a MySQL database

I am attempting to make a POST call from a JavaScript file to a PHP file in order to insert a variable into a MySQL database. Here are the basic files I am working with: 1° PHP file for sending the call <html> <head> <script ...

Are there any advantages to using arrays with non-contiguous indices that outweigh their drawbacks?

When working with JavaScript arrays, it's important to note that arrays can have gaps in their indices, which should not be confused with elements that are simply undefined: var a = new Array(1), i; a.push(1, undefined); for (i = 0; i < a.length; ...