I have been stuck for days on this and looked through many articles, but can not find a script that can help me.
The basis of the script is to automatically get authorization token, before I use a POST
method.
As said before when getting a access token for this particular API the grant type is Client Credentials
and the following fields are needed when manually getting the token:-
Token Name
, Grant Type
, Access Token URL
, Client ID
, Client Secrect
, Scope
and Client Authentication
.
Is there a simple script that I can do this for me before actually doing the POST
as it tiresome manually getting the token.
Just an update I have found a way of actually getting the token now, so if you do the following:
This will get you your token, I now need to find a way to either extract the token in a new request or find a way of putting this in the pre-request scripts, so I am able to enter the data need as 'raw' JSON.
Again if anyone can help, would appreciate it.
Would this be any help to you? Or at least get you closer to what you need?
If you add this script to the Collection
level pre-request script
it will get the token and set this as the jwt
variable. You can use this variable in the Headers
for the main requests, using the {{jwt}}
syntax - This script also gets the expiry_in
value from the token response and sets this as a variable.
On each request in the collection, it will run the script and check to see if you have the AccessTokenExpiry
and jwt
properties in the environment file, it also checks to see if the token has expired. If any of those statements are true, it will get another token for you. If those are ok, it will use what you have set.
const moment = require('moment')
const getJWT = {
url: `<your token base path>/Auth/connect/token`,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: 'grant_type', value: 'client_credentials'},
{key: 'scope', value: '<scope details>'}
{key: 'client_id', value: 'your creds'}
{key: 'client_secret', value: 'your creds'}
]
}
}
var getToken = true
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry')
|| !_.has(pm.environment.toObject(), 'jwt')
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) {
} else {
getToken = false
}
if (getToken) {
pm.sendRequest(getJWT, (err, res) => {
if (err === null) {
pm.environment.set('jwt', `Bearer ${res.json().access_token}`)
var expiryDate = moment().add(res.json().expires_in, 's').valueOf()
pm.environment.set('AccessTokenExpiry', expiryDate)
}
})
}
To access the Collection level elements, if you hover over the collection name and click the ...
icon, this will display a list of menu options. Select edit
.