Search code examples
amazon-web-servicesflaskamazon-cognito

Flask Cognito JWT | Public key not found in jwks.json


I'm having issues using Flask-Cognito getting the following error:

{ "description": "Public key not found in jwks.json", "error": "Invalid Cognito Authentication Token" }

I'm using a user pool that I've checked using lambdas and other cookies authentication frameworks..

my Flask Code is basically the github example:

# configuration
from flask import Flask
from flask_cognito import cognito_auth_required, current_user, current_cognito_jwt
from flask import jsonify
from flask_cognito import CognitoAuth

app = Flask(__name__)
# initialize extension
# cogauth = CognitoAuth(app)
app.config.update({
    'COGNITO_REGION': 'eu-xxxx',
    'COGNITO_USERPOOL_ID': 'eu-xxxx_xxxx',

    # optional
    'COGNITO_APP_CLIENT_ID': 'xxxxx',  # client ID you wish to verify user is authenticated against
    'COGNITO_CHECK_TOKEN_EXPIRATION': False,  # disable token expiration checking for testing purposes
    'COGNITO_JWT_HEADER_NAME': 'Authorization',
    'COGNITO_JWT_HEADER_PREFIX': 'Bearer',
})
CognitoAuth(app)

@app.route('/api/private')
@cognito_auth_required
def api_private():
    # user must have valid cognito access or ID token in header
    # (accessToken is recommended - not as much personal information contained inside as with idToken)
    return jsonify({
        'cognito_username': current_cognito_jwt['username'],  # from cognito pool
        'user_id': current_user.id,  # from your database
    })

I'm calling the API like:

curl --location 'http://127.0.0.1:5000/api/private' \
--header 'Authorization: Bearer XXXX'

Please Help, what am I doing wrong here?


Solution

  • The exception is raised if the public information from the JWKS_URI is not downloaded.

    This could be a result of the JWKS_URI being constructed wrong.

    For flask_awscognito integration you should set these properties:

    1. AWS_DEFAULT_REGION
    2. AWS_COGNITO_DOMAIN
    3. AWS_COGNITO_USER_POOL_ID
    4. AWS_COGNITO_USER_POOL_CLIENT_ID
    5. AWS_COGNITO_USER_POOL_CLIENT_SECRET
    6. AWS_COGNITO_REDIRECT_URL
    app.config.update({
        'AWS_COGNITO_REGION': 'eu-xxxx',
        'AWS_COGNITO_USER_POOL_ID': 'eu-xxxx_xxxx',
    
        # optional
        'AWS_COGNITO_USER_POOL_CLIENT_ID': 'xxxxx',  # client ID you wish to verify user is authenticated against
        'COGNITO_CHECK_TOKEN_EXPIRATION': False,  # disable token expiration checking for testing purposes
        'COGNITO_JWT_HEADER_NAME': 'Authorization',
        'COGNITO_JWT_HEADER_PREFIX': 'Bearer',
    })