Following the documentation from https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html after successfully retrieving an authentication code.
As far as I can tell this is exactly how the request is supposed to be setup:
import request from 'request'
function fetchToken(code: any, clientId: string, clientSecret: string) {
try {
let tokenEndpoint = `https://example.auth.us-east-1.amazoncognito.com/oauth2/token`
const clientIdEncoded = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
request.post({
url:tokenEndpoint,
headers: {
'Content-Type':'application/x-www-form-urlencoded',
'Authorization':`Basic ${clientIdEncoded}`
},
form: {
code,
'grant_type':'authorization_code',
'client_id':clientId,
'redirect_uri':'http://localhost:3000'
}},
function(err,httpResponse,body){
console.log(httpResponse.statusCode)
//400
console.log(httpResponse.statusMessage)
//Bad Request
if(err) {
console.error(err)
}
console.log(body)
//{"error":"unauthorized_client"}
})
} catch (error) {
console.error(error)
}
}
Why would be getting unauthorized_client
? Is there an easier way to debug this?
Edit: tested this in Postman with the same request and getting the same error
Headers Body
Authenticating with tokensWhen a user signs into your app, Amazon Cognito verifies the login information. If the login is successful, Amazon Cognito creates a session and returns an ID, access, and refresh token for the authenticated user.
For request parameter-based Lambda authorizers 401 Unauthorized errors usually occur when configured identity sources are missing, null, empty, or not valid. To troubleshoot this type of error, verify the information that must be included in requests to your API by reviewing your Lambda authorizer's configuration.
These endpoints are available from https://cognito-idp.REGION.amazonaws.com/USER-POOL-ID. More information about these endpoints is available here.
Amazon Cognito requires that your redirect URI use HTTPS, except for http://localhost , which you can set as a callback URL for testing purposes. Amazon Cognito also supports app callback URLs such as myapp://example .
Please check if the Cognito User Pool App is using secret key. If you have created with secret key option, that must be included in the Authorization
header of the request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With