cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Get OAuth2 access token via Javascript

WayneSG
Participant
0 Likes
3,934

I am using below code to fetch the token from Event Mesh server, it succeeded with no error.

However, this token is incorrect, the length is only 1601, and the correct token length shall be 1869.

This causes the next code block of publishing an event to SAP event mesh failed with unauthorized error message.

Did anyone succeed to get a correct token before? Please help, thanks.

const fetch = require('node-fetch');

async function getEMAccessToken() {
    const EMTokenURL = 'your-token-url';
    const EMClientID = 'your-client-id';
    const EMClientSecret = 'your-client-secret';

    const credentials = Buffer.from(`${EMClientID}:${EMClientSecret}`).toString('base64');

    const response = await fetch(EMTokenURL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Basic ${credentials}`
        },
        body: 'grant_type=client_credentials'
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data.access_token;
}
View Entire Topic
martinstenzig
Contributor
0 Likes

Don't know if it makes a difference, but I usually attach then credentials to the body, not the header...

 // specify form parameters
      const formParams = new URLSearchParams()
      formParams.append('grant_type', 'client_credentials')
      formParams.append('client_id', '[clientIdValue]')
      formParams.append('client_secret', '[client secret value]')

      // Assemble the post options
      const postOptions = {
        method: 'POST',
        headers: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        body: formParams
      }

      // console.log('Post options: ', tokenUrl, post_options);
      fetch(tokenUrl, postOptions)
        .then(res => res.json())
...
WayneSG
Participant
0 Likes

Hi Martin,

Thanks for your suggestion, I follow your example, below is my revised codes. However, after testing, the result is same, it will retrieve an incorrect access token string of 1601 length.

Note: Below codes block is for reference, it does not solve the token issue.

async function getEMAccessToken() {

const EMTokenURL = tokenUrl;

const EMClientID = clientId;

const EMClientSecret = clientSecret;

// specify form parameters

const formParams = new URLSearchParams();

formParams.append('grant_type', 'client_credentials');

formParams.append('client_id', EMClientID);

formParams.append('client_secret', EMClientSecret);

// Assemble the post options

const postOptions = {

method: 'POST',

headers: {

'Content-type': 'application/x-www-form-urlencoded'

},

body: formParams

};

const response = await fetch(EMTokenURL, postOptions);

if (!response.ok) {

throw new Error(`HTTP error! status: ${response.status}`);

}

const data = await response.json();

return data.access_token;

}