Skip to main content

Async Auth Middleware for FastAPI/Starlette

Project description

auth-middleware

Async Auth Middleware for FastAPI/Starlette.

Installation

Using pip:

pip install auth-middleware

Using poetry

poetry auth-middleware

How to use it

Auth Middleware follows the middleware protocol and, therefore, should be added as a middleware to your FastApi or Starlette application.

The steps, using FastAPI:

from fastapi import FastAPI, Depends

from starlette.requests import Request
from starlette.responses import Response

# Step 1: import the functions to control authentication
from auth_middleware.functions import require_groups, require_user
# Step 2: import the Middleware to use
from auth_middleware.jwt_auth_middleware import JwtAuthMiddleware
# Step 3: import the auth provider
from auth_middleware.providers.cognito import CognitoProvider

app: FastAPI = FastAPI()

# Step 4: Add Middleware with a Cognito auth Provider
app.add_middleware(JwtAuthMiddleware, auth_provider=CognitoProvider())

@app.get("/",
    dependencies=[
        # Step 5: add the authorization dependencies you want: require_user or requiere_groups
        # Depends(require_groups(["customer", "administrator"])),
        Depends(require_user()),
    ],)
async def root(request: Request):
    # Step 6: user information will be available in the request.state.current_user object
    return {"message": f"Hello {request.state.current_user.name}"}

Then set the environment variables (or your .env file)

AWS_COGNITO_USER_POOL_ID=your_cognito_user_pool_id
AWS_COGNITO_USER_POOL_REGION=your_cognito_user_pool_region

Call the method sending the id_token provided by Cognito:

curl -X GET http://localhost:8000/ -H "Authorization: Bearer MY_ID_TOKEN"

Middleware configuration

The middleware configuration is done by environment variables (or using and .env file if your project uses python-dotenv).

The main variables are shwon in the table below:

Name Description Values Default
AUTH_MIDDLEWARE_LOG_LEVEL Log level for the application DEBUG, INFO, WARNING, ERROR, CRITICAL INFO
AUTH_MIDDLEWARE_LOG_FORMAT Log format See python logger documentation %(log_color)s%(levelname)-9s%(reset)s %(asctime)s %(name)s %(message)s
AUTH_MIDDLEWARE_LOGGER_NAME Auth middleware logger name A string auth_middleware
AUTH_MIDDLEWARE_DISABLED Auth middleware enabled/disabled false, true false
AUTH_MIDDLEWARE_JWKS_CACHE_INTERVAL_MINUTES JWKS keys file refreshing interval An integer value 20
AUTH_MIDDLEWARE_JWKS_CACHE_USAGES JWKS keys refreshing interval (counter) An integer value 1000

The User property

After authentication the Request object contains ifnormation about the current user in the state.current_user variable.

The table below shows the properties of the user object.

Property Description
id Id of the user in the identity provider
name User name (or id if not defined)
email User email (if any)
groups Array of user groups as sent by the identity provider

Control authentication and authorization

There are two utility functions to control the authentication and authorization. These functions return an HttpException if the auth/authn fails.

The functions can be invoked directly or can be used as a dependency in frameworks as FastAPI.

To check if a user is logged in use require_user:

require_user()

To check if a user has assigned a group or groups use require_groups:

require_groups(["group1", "group2"])

Authentication providers

Amazon Cognito

TODO

Azure Entra ID

TODO

Google Idp

TODO

Custom auth provider

TODO

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

auth_middleware-0.1.6.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

auth_middleware-0.1.6-py3-none-any.whl (15.9 kB view details)

Uploaded Python 3

File details

Details for the file auth_middleware-0.1.6.tar.gz.

File metadata

  • Download URL: auth_middleware-0.1.6.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.2 Linux/6.5.0-1017-azure

File hashes

Hashes for auth_middleware-0.1.6.tar.gz
Algorithm Hash digest
SHA256 e7ec015fee817e4d9abe2b77a9f6e4a0d1dec40382b859cb13c2d3f8d9d04f32
MD5 a04d4248a6991b6a617af06e7dec8506
BLAKE2b-256 f9001bb6f655942d31ac710650fce1afa17b63d01b111b1550fb7b6045316f54

See more details on using hashes here.

File details

Details for the file auth_middleware-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: auth_middleware-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 15.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.2 Linux/6.5.0-1017-azure

File hashes

Hashes for auth_middleware-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 0faa7017a2c396aa3d0e4463cbf34af2f8bddde486f3bc8c55f506573c898e9d
MD5 bec0e632aa2663390ae4ffcc60b60f31
BLAKE2b-256 187df9d6bf43f3eddf7fee04865c0cc72bc5c6bc3c3499d9693e4f9f28fd77e5

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