I have a collection in Postman which all connects to the Google API, I want to implement the Auth2.0 at collection level as a pre-request script in order to generate an access token. I am using the following code to do so:
let callbackUrl = 'xxxxxxxxx';
let authUrl = 'https://accounts.google.com/o/oauth2/auth';
let tokenUrl = 'https://oauth2.googleapis.com/token';
let clientId = 'xxxxxxxxx';
let clientSecret = 'xxxxxxxxxxxx';
let scope = 'xxxxxxxxx'
let getTokenRequest = {
method: 'POST',
url: tokenUrl,
auth: {
type: "basic",
basic: [
{ key: "username", value: clientId },
{ key: "password", value: clientSecret }
]
},
body: {
mode: 'formdata',
formdata: [
{ key: 'grant_type', value: 'authorization_code' },
{ key: 'redirect_uri', value: callbackUrl },
{ key: 'authUrl', value: authUrl },
{ key: 'scope', value: scope }
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
let jsonResponse = response.json(),
newAccessToken = jsonResponse.access_token;
console.log({ err, jsonResponse, newAccessToken })
pm.environment.set('accessToken', newAccessToken);
pm.variables.set('accessToken', newAccessToken);
});
If I run this I get back
“Missing required parameter: code”
in the postman console. I can see the issue is I am not submitting a code parameter as when I merely generate a token from the UI without using pre-request scripts i am showing this in my postman console:
grant_type:"authorization_code"
code:"4/rgGpWyiaxxxxxxxx6j3EZANLDPmHHxxxxxxxxxxxxxxxxxxxo6bRnbBZovn1T-Setccccccccccccccccccccccccccccccccccccccccccccccxxxxxxxxxxx"
redirect_uri:"xxxxxxxx"
client_id:"xxxxxxxx"
My question is where does this code originate from? I am assuming postman generates it as it is part of my Request Body? And how do I generate it to add to my request body as part of my pre-request script?