user1555245
user1555245

Reputation: 135

Axios 400 Bad Request Cognito JWT generation in Node Js

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

Answers (1)

dangle
dangle

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

Related Questions