on 01-09-2024 10:04 AM
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;
}
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())
...
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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;
}
User | Count |
---|---|
77 | |
9 | |
9 | |
7 | |
7 | |
6 | |
6 | |
5 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.