Skip to content

Amazon Cognito Token Endpoint Returns invalid_client

0

Hello,

I am using Amazon Cognito with Authorization Code Grant with PKCE. When I attempt to call the /oauth2/token endpoint, it returns {"error":"invalid_client"}. I have checked a couple of similar posts (here and here) but still have the issue.

Here is some sample code:

import base64
import requests

AMAZON_COGNITO_CLIENT_ID = "example_client_id"
AMAZON_COGNITO_CLIENT_SECRET = "example_client_secret"
AMAZON_COGNITO_TOKEN_ENDPOINT = "https://example_subdomain.auth.us-east-1.amazoncognito.com/oauth2/token"

def test_auth(auth_code, code_verifier):
    auth_data = base64.b64encode(f"{AMAZON_COGNITO_CLIENT_ID}:{AMAZON_COGNITO_CLIENT_SECRET}".encode())
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": f"Basic {auth_data}",
    }
    body = {
        "grant_type": "authorization_code",
        "client_id": AMAZON_COGNITO_CLIENT_ID,
        "code": auth_code,
        "code_verifier": code_verifier,
        "redirect_uri": "http://localhost:5000/auth_redirect",
    }
    response = requests.post(AMAZON_COGNITO_TOKEN_ENDPOINT, headers=headers, data=body)
    print(response.text)

if __name__ == "__main__":
    auth_code = input("Auth code: ")
    code_verifier = input("Code verifier: ")
    test_auth(auth_code, code_verifier)

The output is:

{"error":"invalid_client"}

There is no further description of the error. The authorization data is generated as described here. The code verifier (shown) and code challenge (not shown) were generated as described here and here. The redirect URI is the same sent to the /oauth2/authorize endpoint.

Thanks in advance for your help.

asked 2 years ago3K views

2 Answers
1
Accepted Answer

Despite the documentation, it doesn't seem that Amazon Cognito supports the Basic authentication scheme in the Authorization header when using Authorization Code Grant with PKCE. Once I removed the Authorization header and added the client_id and client_secret to the body (thus using client_secret_post instead of client_secret_basic, as described in the documentation), I was finally able to retrieve the token.

answered 2 years ago

EXPERT

reviewed 2 years ago

EXPERT

reviewed 2 years ago

  • Ensure that you decode the binary to a string by explicitly calling decode:

    auth_data = base64.b64encode(f"{AMAZON_COGNITO_CLIENT_ID}:{AMAZON_COGNITO_CLIENT_SECRET}".encode()).decode()

    This resolves the issue.

0

Ensure that you decode the binary to a string by explicitly calling decode:

auth_data = base64.b64encode(f"{AMAZON_COGNITO_CLIENT_ID}:{AMAZON_COGNITO_CLIENT_SECRET}".encode()).decode()

This resolves the issue.

answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.