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!

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:

1 Like

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.

5 Likes

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

What is missing ? @sivcan

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);

6 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

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);
});
1 Like

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 ?