Skip to main content

Authenticate users to Cognito user pool via JWT.

Project description

Flask-Cognito

Authenticate users based on AWS Cognito JWT.

Initialization

# configuration
app.config.update({
    'COGNITO_REGION': 'eu-central-1',
    'COGNITO_USERPOOL_ID': 'eu-central-1c3fea2',

    # optional
    'COGNITO_APP_CLIENT_ID': 'abcdef123456',  # 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': 'X-MyApp-Authorization',
    'COGNITO_JWT_HEADER_PREFIX': 'Bearer',
})


# initialize extension
from flask_cognito import CognitoAuth
cogauth = CognitoAuth(app)

@cogauth.identity_handler
def lookup_cognito_user(payload):
    """Look up user in our database from Cognito JWT payload."""
    return User.query.filter(User.cognito_username == payload['username']).one_or_none()

Check Authentication

from flask_cognito import cognito_auth_required, current_user, current_cognito_jwt

@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
    })

Restrict access by Cognito Group

from flask_cognito import cognito_auth_required, current_user, current_cognito_jwt

@route('/api/foo')
@cognito_auth_required
@cognito_group_permissions(['admin','developer'])
def api_private():
    # user must belongs to "admin" or "developer" groups
    return jsonify({
        'foo': "bar"
    })

Acknowledgements

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Flask-Cognito-1.21.tar.gz (5.0 kB view details)

Uploaded Source

File details

Details for the file Flask-Cognito-1.21.tar.gz.

File metadata

  • Download URL: Flask-Cognito-1.21.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for Flask-Cognito-1.21.tar.gz
Algorithm Hash digest
SHA256 8daf0a7dd8978c089a55b98e681a6ecab276d19c39828079214f6cb72a508fb5
MD5 4787b136f53e9eaec80c6570dd8e5be3
BLAKE2b-256 21df4ef5d89340665d9bfe6206c263efecb1d0ac4c8b43fc8febe428292ade6f

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page