I am trying to add bearer tocken to all the request calls within the collection.Please help!
Hi @d.rajkhowa02, welcome to our community!
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.
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.
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”
Working fine now just added magic command 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);
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.
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);
});
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!
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!