0
let tokenUrl = 'https://my.url/oauth2/token';
let scope = 'pets/read pets/updage petId/read'

let getTokenRequest = {
    method: 'POST',
    url: tokenUrl,
     header: {
         'Content-Type': 'application/x-www-form-urlencoded',
         Authorization: 'Basic Base64Encode(client_id:client_secret)'}, // encoded manually beforehand
    body: {
        mode: 'formdata',
        formdata: [
            { key: 'grant_type', value: 'client_credentials' },
            { key: 'scope', value: scope }
        ]
    }
};

pm.sendRequest(getTokenRequest, (err, response) => {
    let jsonResponse = response.json(),
    newAccessToken = jsonResponse.access_token;
    
    pm.environment.set('access_token', newAccessToken);
    pm.variables.set('access_token', newAccessToken);
});

Geeks, help, please!

I have API with Cognito authorization (Client Credentials type). It work's fine in Postman with manually 'Request new Access token'. But I want to retrieve token with pre-request script. I relied on AWS documentation about token endpoint. I have

JSONError: No data, empty input at 1:1

in the console. Do you have any suggestions?

1 Answers1

0

I've encountered the same problem and resolved it by setting grant_type and scope as query string in the url:

let tokenUrl = pm.variables.get("cognito-url")+ "/oauth2/token?grant_type=client_credentials&scope=' + pm.variables.get("cognito-scope");
let auth_code = btoa(pm.variables.get("cognito-client-id") + ":" + pm.variables.get("cognito-client-secret"))
    
    let getTokenRequest = {
        method: 'POST',
        url: tokenUrl,
        header: {
             'Content-Type': 'application/x-www-form-urlencoded',
             'Authorization': 'Basic ' + auth_code}
    };
    
    pm.sendRequest(getTokenRequest, (err, response) => {
        let jsonResponse = response.json(),
        newAccessToken = jsonResponse.access_token;
        
        pm.environment.set('access_token', newAccessToken);
        pm.variables.set('access_token', newAccessToken);
    });
RudyVerboven
  • 1,204
  • 1
  • 14
  • 31