How to automatically set a Bearer Token for your Postman requests?

I am trying to add bearer tocken to all the request calls within the collection.Please help!

1 Like

Hi @d.rajkhowa02, welcome to our community! :vulcan_salute:

I use this in my context, I put this piece of code on my collection Pre-Request Scritps.

pm.sendRequest({
    url: YourURL
    method: 'POST',
    header: {
        'content-type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ YOUR PARAM TO CREATE THE TOKEN IF NEED IT })
    }
}, (err, res) => pm.collectionVariables.set("TOKEN", res.json().accessToken));

Then on collection Authorization I insert the variable TOKEN and change the Type to Bearer Token. That will help on your problem.

:vulcan_salute:

2 Likes

Hi @d.rajkhowa02

You can do in other way also .Set a environment variable with the name Token . Below are the script you can write down inside Test tab.

var res = JSON.parse(responseBody);
if(data.KeyName === ‘Your API KEY Name’)
{
pm.environment.set(“Your variable name”, res.token);
}

it will save the token value inside the variable what you declared in environment .

For this you have to make a csv file with two field Key name and Keyvalue .that can be passed with the help of post man runner,select your environment there .

Defiantly it ll work .I have done in the same way.

3 Likes

When i added this request in prerequest, it gives me same Token Expired Error ‘401’

What is missing ? @singhsivcan

var authServiceUrl = pm.environment.get('TOKEN_URL');
var cname = pm.environment.get('UNAME');
var cpword = pm.environment.get('PWD_ENCRYPTED');
var cID = pm.environment.get('CLIENT_ID');
var cSECR = pm.environment.get('CLIENT_SECRET');

pm.sendRequest({
    url: authServiceUrl+'/token',
    method: 'POST',
header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
            mode: 'urlencoded',
            urlencoded: [
                    { key: "client_id", value: 'cID' },
                    { key: "clientSecret", value: 'cSECR' },
                    { key: "username", value: 'cname' },
                    { key: "password", value: 'cpword' },
            ]
    }
    });

also changed url: authServiceUrl + “/token”

1 Like

Working fine now just added magic command :slight_smile: for wach key values.
{ key: "client_id", value: 'cID', enabled:true},

two lines of code actually, work for me Kindly add this in the test field

var res = pm.response.json();
pm.environment.set('token', res.data.token);

5 Likes

For the record, you can do all of this from within a pre-request script at the collection level so you never have to worry about a token expiring again.

1 Like

Hi Rumbiiha,

Thank You for sharing the solution. Can you please let me know, How do I pass the url, username and password from where token is generated?

Thank You

[quote=“descent-module-astr3, post:8, topic:10126, full:true”]
Hi Rumbiiha,

Thank You for sharing the solution. Can you please let me know, How do I pass the url, username and password from where token is generated?

so in case you want to set the password then you will have to set it manually in the environment because it’s not recommended to return the password in the response may be when a user is logging in or out.
but in case it’s in the body too then you can also extract it and set it automatically using the script

var res = pm.response.json();
pm.environment.set('password', res.data.password);
pm.environment.set('email', res.data.email);

so it’s more of like javascript and you can use dot to access what you want

an example of response is like so
{
“status”: 201,
“data”: {
“email”: “example@email.com”,
}
}

but make sure that the headers are set properly to allow environmental variables

1 Like

Hi @gpub1,

Initially, I saw the same error. I made few changes to my script and it worked.
Try the below pre-request script. Add the ‘Token’ variable as an environment variable.

var authServiceUrl = pm.environment.get('TOKEN_URL');
var cname = pm.environment.get('UNAME');
var cpword = pm.environment.get('PWD_ENCRYPTED');
var cID = pm.environment.get('CLIENT_ID');
var cSECR = pm.environment.get('CLIENT_SECRET');

const getTokenRequest = {
  method: 'POST',
  url: authServiceUrl+'/token',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
      mode: 'urlencoded',
      urlencoded: [
          { key: 'username', value: cname },
          { key: 'password', value: cpword },
          { key: 'client_id', value: cID },
          { key: 'client_secret', value: cSECR },
      ]
  }
};

pm.sendRequest(getTokenRequest, (err, response) => {
  const jsonResponse = response.json();
  const newAccessToken = jsonResponse.access_token;

  pm.variables.set('Token', newAccessToken);
});
2 Likes

Is the api-key same as tenant or is it the client_id and client_secret?

How do u then put this into the call it self ?

As this question is still pulling lots of views I’ve created a collection based on @danny-dainton 's blog post that shows how you can dynamically set/refresh a Bearer token before sending a request. You can fork it here: Postman

Do read the documentation and update the collection variables before using it!

3 Likes

I think you do worked auth token and wonna to use in global cases.
3 dots edit and


This authorization method will be used for every request in this folder. You can override this by specifying one in the request.
So you can add for folder or other alls.

thank you @rumbiiha-swaib. It saves tons of time.

This worked like a charm. In addition I set a Bearer token auth option on main folder and used inherit from parent there for sub routes.

This worked beautifully for me. I know it is late in the game, but just wanted to give my feedback. Thanks!

I am using a variable at the Collection level

and passing it in the authorization header like below

for me below code on the Tests tab for the Authorization request worked fine.

var jsonData = JSON.parse(responseBody);
pm.collectionVariables.set('token', jsonData.access_token);
3 Likes