Skip to main content

Basic AWS cognito authentication package for FastAPI

Project description

FastAPI - Cognito

FastAPI Cognito library is Python library which is built to ease usage of AWS Cognito authentication with FastAPI framework. This library provides basic functions/tools which allows developers to use Cognito JWT. In the future, tools/functionalities may be extended. This library is inspired on Flask-Cognito library created by JetBridge.

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:

  • Add all required imports
from fastapi_cognito import CognitoAuth, CognitoSettings, AuthHeaderPlugin
from fastapi import FastAPI

from starlette_context import plugins
from starlette_context.middleware import RawContextMiddleware

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

Note: These configurations are required

You should also import BaseSettings from pydantic if you are going to use global BaseSettings object.

  • Provide settings that are mandatory for CognitoAuth library.
class Settings(BaseSettings):

    check_expiration = True
    jwt_header_name = "Authorization"
    jwt_header_prefix = "Bearer"
    userpools = {
      "europe": {
        "region": "COGNITO_REGION",
        "userpool_id": "COGNITO_USERPOOL_ID",
        "app_client_id": "APP_CLIENT_ID"
      }
      ...
    }

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

  • Initialize application and settings object, also initialize CognitoAuth and pass previously created settings as settings param.
app = FastAPI()
settings = Settings()
cognito = CognitoAuth(settings=CognitoSettings.from_global_settings(settings))
  • Add middleware for request context. This is required for CognitoAuth to work.
app.add_middleware(
    RawContextMiddleware,
    plugins=(
        plugins.RequestIdPlugin(),
        plugins.CorrelationIdPlugin(),
        AuthHeaderPlugin()
    )
)
  • This example below shows a simple endpoint that is protected by Cognito, decorator is doing all the work about decoding and verifying Cognito JWT from request Authorization header and storing it in token param. It can be used later to add more security to endpoints and to get required data about user which token belongs to. Endpoint will use default userpool if userpool_name param was not provided.
@app.get("/")
@cognito.cognito_auth_required()
def hello_world():
  # This method will get token from request context
  token = cognito.get_token()
  # This method will retrieve Cognito ID from token stored in request context
  cognito_id = cognito.get_cognito_id()
    return {"message": "Hello world"}

You can also change userpool that should be used when calling cognito_auth_required() method by passing userpool_name param. If userpool_name param is not provided, default userpool will be used.

@app.get("/")
@cognito.cognito_auth_required(userpool_name="europe")
def hello_world():
    return {"message": "Hello world"}

There are some additional methods such as check_cognito_groups(token, groups) which will check if cognito:groups value from token param matches the value passed in groups param, and it will restrict or allow access to users. This method is not fully tested, and it may produce some problems.

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

fastapi-cognito-1.0.0.tar.gz (8.9 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-1.0.0-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-cognito-1.0.0.tar.gz.

File metadata

  • Download URL: fastapi-cognito-1.0.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.8.6

File hashes

Hashes for fastapi-cognito-1.0.0.tar.gz
Algorithm Hash digest
SHA256 095cacfe6e4d1765d3c7598ed8b3eceb07cee65f6d7b1d77100cf258c2d25acf
MD5 de83f3b683296239edf60de24de5c45c
BLAKE2b-256 1966e243e0d76bbcbcff5904292aa44ce1daa3ad170263f1154e499da7e1875a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_cognito-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 8.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.8.6

File hashes

Hashes for fastapi_cognito-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6964f9c8320effafceb6691e5983c4367252348e84160214e7f70622e1bc41fb
MD5 fb05eddcf24aab4d53e15062a99851a7
BLAKE2b-256 8f4ce95b31e6776092f04d19334b79b215bd8687c72ae72276d9bea0b11df273

See more details on using hashes here.

Supported by

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