Skip to main content

FastAPI - Cognito

FastAPI library that ease usage of AWS Cognito Auth. This library provides basic functionalities for decoding, validation and parsing Cognito JWT tokens and for now it does not support sign up and sign in features.

Library supports both HTTP and WebSocket connection auth.

Requirements

  • Python >=3.8
  • FastAPI
  • AWS Cognito Service

How to install

Pip Command

pip install fastapi-cognito

How to use

This is the simple example of how to use this package:

  • Create app
from fastapi import FastAPI

app = FastAPI()

All mandatory fields are added in CognitoSettings BaseSettings object. Settings can be added in different ways. You can provide all required settings in .yaml or .json files, or your global BaseSettings object. Note that userpools field is Dict and FIRST user pool in a dict will be set as default automatically if userpool_name is not provided in CognitoAuth object. All fields shown in example below, are also required in .json or .yaml file (with syntax matching those files.)

  • Provide settings that are mandatory for CognitoAuth to work. You can provide one or more userpools.
    • app_client_id field for userpool besides string, can contain multiple string values provided within list, tuple or set
from pydantic_settings import BaseSettings
from pydantic.types import Any

class Settings(BaseSettings):
    check_expiration: bool = True
    jwt_header_prefix: str = "Bearer"
    jwt_header_name: str = "Authorization"
    userpools: dict[str, dict[str, Any]] = {
        "eu": {
            "region": "USERPOOL_REGION",
            "userpool_id": "USERPOOL_ID",
            "app_client_id": ["APP_CLIENT_ID_1", "APP_CLIENT_ID_2"] # Example with multiple ids
        },
        "us": {
            "region": "USERPOOL_REGION",
            "userpool_id": "USERPOOL_ID",
            "app_client_id": "APP_CLIENT_ID"
        },
        ...
    }

settings = Settings()

This example below shows how global BaseSettings object can be mapped to CognitoSettings and passed as param to CognitoAuth. If we were using .yaml or .json, we should call .from_yaml(path) or .from_json(path) methods on CognitoSettings object.

  • Instantiate CognitoAuth and pass previously created settings as settings param.
from fastapi_cognito import CognitoAuth, CognitoSettings

# default userpool(eu) will be used if there is no userpool_name param provided.
cognito_eu = CognitoAuth(
  settings=CognitoSettings.from_global_settings(settings)
)
cognito_us = CognitoAuth(
  settings=CognitoSettings.from_global_settings(settings), userpool_name="us"
)
  • This is a simple endpoint that requires authentication, it uses FastAPI dependency injection to resolve all required operations and get Cognito JWT.
from fastapi_cognito import CognitoToken
from fastapi import Depends

@app.get("/")
def hello_world(auth: CognitoToken = Depends(cognito_eu.auth_required)):
    return {"message": "Hello world"}

Optional authentication

If authentication should be optional, we can use cognito_eu.auth_optional

Example:

from fastapi_cognito import CognitoToken
from fastapi import Depends

@app.get("/")
def hello_world(auth: CognitoToken = Depends(cognito_eu.auth_optional)):
    return {"message": "Hello world"}

Custom Token Model

This feature adds possiblity to use any token type for authentication(e.g. parsing ID token).

In case your token payload contains additional values, you can provide custom token model instead of CognitoToken. If there is no custom token model provided, CognitoToken will be set as a default model. Custom model should be provided to CognitoAuth object, and should be set as type of auth variable for endpoint dependency.

Example:

class CustomTokenModel(CognitoToken):
    custom_value: Optional[str] = None


cognito = CognitoAuth(
    settings=CognitoSettings.from_global_settings(settings),
    # Here we provide custom token model
    custom_model=CustomTokenModel
)

@app.get("/")
# Type of `auth` should be custom token Class
def hello_world(auth: CustomTokenModel = Depends(cognito.auth_required)):
    return {"message": f"Hello {auth.custom_value}"}

Custom Cognito attributes

Custom attributes in Cognito starts with custom:, which is the issue for parsing this variable with pydantic because of the colon. To parse custom attributes, add the full name of Cognito attribute to Pydantic Field alias.

class CustomTokenModel(CognitoToken):
    custom_value: Optional[str] = Field(alias="custom:custom_attr")

Pydantic will automatically parse value by alias if specified. Make sure that you have default value set if attribute is optional.

OpenAPI docs authentication

To use tokens to authenticate requests using OpenAPI docs, you can create wrapper class.

from fastapi.security import HTTPBearer
from starlette.requests import Request
from fastapi_cognito import CognitoToken

class CognitoAuth(HTTPBearer):
    async def __call__(self, request: Request) -> CognitoToken:
        return await cognito.auth_required(request=request)

cognito_auth = CognitoAuth()

@router.get("/")
async def test_endpoint(auth: CognitoToken = Depends(cognito_auth)):
    return JSONResponse(
        status_code=200, content={"detail": "Success"}
    )

This will show button for adding authentication token to the request.

Using custom JWKS URL for userpool

If you need to use custom JWKS URL for userpool, for example when you're running cognito-local for local development, you can specify JWKS_URL configuration per userpool.

class Settings(BaseSettings):
    userpools: dict[str, dict[str, Any]] = {
        "eu": {
            "region": "USERPOOL_REGION",
            "userpool_id": "USERPOOL_ID",
            "app_client_id": "APP_CLIENT_ID",
            "jwks_url": "https://local-cognito-idp:port/jwks.json"
        }
        ...
    }

By setting this configuration, CognitoAuth will automatically use this url to retrieve JWKS for userpool. If configuration is not set, CognitoAuth will generate URL in the following format https://cognito-idp.<region>.amazonaws.com/<userpool_id>/.well-known/jwks.json and will use that URL to retrieve JWKS.

There is global configuration through environment variable AWS_COGNITO_KEYS_URL which is supported for backward compatibility with previous dependency on cognitojwt library. CognitoAuth will prioritise in the following order:

  • jwks_url configuration per userpool,
  • AWS_COGNITO_KEYS_URL environment variable if set,
  • default value of https://cognito-idp.<region>.amazonaws.com/<userpool_id>/.well-known/jwks.json

Download files

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

Source Distribution

fastapi_cognito-2.10.0.tar.gz (65.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_cognito-2.10.0-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_cognito-2.10.0.tar.gz.

File metadata

  • Download URL: fastapi_cognito-2.10.0.tar.gz
  • Upload date:
  • Size: 65.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for fastapi_cognito-2.10.0.tar.gz
Algorithm Hash digest
SHA256 b710c52a7a626f8e03437975aa105592da080dcc28b93bb14a8c2f4ab3e97e8c
MD5 c358e75755240ee5cf5c2bdd871a1f03
BLAKE2b-256 07ca9938b66293cf366c96688a10d384f49bd362b53a80ccee004af7762d9d8e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_cognito-2.10.0.tar.gz:

Publisher: publish.yaml on markomirosavljev/fastapi-cognito

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_cognito-2.10.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_cognito-2.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6c4c33fdea83981a64d6659add8609a0b34983f1c10ed95669d813336a4f5093
MD5 9cce05aa8795356c8cd7f18a3f1aa91f
BLAKE2b-256 20b62fb978e998a32458b2f647b398c5c7a410afc21e85b25dc64f692d155053

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_cognito-2.10.0-py3-none-any.whl:

Publisher: publish.yaml on markomirosavljev/fastapi-cognito

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

2.10.0 This release

2 files

2.9.0

2 files

2.8.0

2 files

2.7.0

2 files

2.6.0

2 files

2.5.0

2 files

2.4.2

2 files

2.4.1

2 files

2.4.0

2 files

2.3.0

2 files

2.2.1

2 files

2.1.0

2 files

2.0.5

1 file

2.0.4

1 file

2.0.3

2 files

2.0.2

2 files

2.0.1

2 files

2.0.0

2 files

1.1.0

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page