Reputation: 135
I am trying to create Cognito JWtoken via POST call with axios in Lambda function using node js , but i am getting error 400 bad request. In parallel it is working fine in Postman.
Code :
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token', {
grant_type: grantType, // This is the body part
redirect_uri: redirectURI,
client_id: clientid,
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
});
Upvotes: 1
Views: 2068
Reputation: 41
You need to URL encode the body of your request into a single string. You can use querystring.stringify
to do this.
let data = querystring.stringify({
grant_type: 'grantType',
redirect_uri: 'redirectURI',
client_id: 'clientid',
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
})
=> 'client_id=clientid&code=fb06a2dd-XXXXXXXXX-f186c6302806&grant_type=grantType&redirect_uri=redirectURI'
Then your request will look like this:
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token',
data,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})
Upvotes: 4