Postman Pre-request Script. request for /auth/oauth/token

I’m going to try my best to explain what my issue is right now. It’s a pretty complicated test for me being pretty new!

in my test, there are 2 sites and i start off the collection by getting an Auth token which I use for the whole collection. Now, for this test though I need to have an API call to a different site that uses a different Auth token. so I need to start out my test in the pre-request by generating a new auth token.

I’m trying to have a POST request to generate a new token in PreRequest script . this token needs to use Basic Auth with username and password and I’m not sure how i can add that into pre-request script. do i add my username and password in the header like so below? or what is the best practice for hard coding a call like this which seems to usually be the main request in testing

var createRequest = {
url: pm.environment.get(“baseURL”) + “/api/…/token”,
method: ‘POST’,
header: {
“Content-Type”: “application/x-www-form-urlencoded”,
"Authorization": {
** username: “username”,**
** password: “password”},**
“Accept”: “/
},

It took me a while to reach to this:

let keys = clientId + “:” + clientSecret;
let encodedKeys = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(keys));

const getTokenRequest = {
method: ‘POST’,
url: authUrl,
header: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Authorization’: 'Basic ’ + encodedKeys,
},
body: {
mode: ‘urlencoded’,
urlencoded : [
{ key: ‘grant_type’, value: ‘client_credentials’ }
]
}
};

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

pm.variables.set(‘access_token’, newAccessToken);
});

1 Like

My header was form-data at first on redployment it was changed to urlencoded
so first this worked
// mode: ‘formdata’,
// formdata: [
// { key: ‘grant_type’, value: ‘client_credentials’ },
// { key: ‘client_id’, value: clientId },
// { key: ‘client_secret’, value: clientSecret }
but later this worked
mode: ‘urlencoded’,
urlencoded : [
{ key: ‘grant_type’, value: ‘client_credentials’ }
]

Thank you for the response, it helped me.

But
Still CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(keys)); is NOT working for me

was able to pass
header: {‘Content-Type’:‘application/x-www-form-urlencoded’,‘Authorization’: 'Basic ###### (value here)},
and successfully obtain response so the other code is working,

But headers is being taken as
Request Headers

Content-Type: application/x-www-form-urlencoded

Authorization: Basic CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(keys))