A robust bearer token authentication and authorization middleware for FastAPI applications.
Project description
FastAPI Bearer Authorization
A robust bearer token authentication and authorization middleware for FastAPI applications.
[!WARNING]
This project is in early development and may not be suitable for production use.
Features
- Easy-to-use bearer token authentication
- Fine-grained permission-based authorization using unique operation IDs
- Configurable via environment variables or direct configuration
- Secure token generation and validation
Installation
pip install fastapi-bearer-authzn
Quick Start
from fastapi import FastAPI, Depends
from fastapi_bearer_authzn import BearerAuthDependency, bootstrap_config, ConfigModel
# Generate a sample configuration with tokens
config_dict, tokens = bootstrap_config(no_identities=3)
config = ConfigModel.model_validate(config_dict)
# Initialize the auth dependency
auth = BearerAuthDependency(config=config)
app = FastAPI()
@app.get("/protected")
def protected_route(user_id: str = Depends(auth)):
return {"message": "Access granted", "user_id": user_id}
Configuration Structure
The configuration is structured as follows:
from fastapi_bearer_authzn import ConfigModel, PermissionConfig
config_dict = {
"user_id_1": PermissionConfig(
hashed_token="...",
user_identifier="user1@example.com",
permissions=["operation_id_1", "operation_id_2"]
),
"user_id_2": PermissionConfig(
hashed_token="...",
user_identifier="user2@example.com",
permissions=["*"] # Wildcard for all permissions
)
}
config = ConfigModel.model_validate(config_dict)
You can use the bootstrap_config(no_identities=n)
function to generate a sample configuration with n
number of identities. This function returns both the configuration dictionary and a dictionary of tokens:
config_dict, tokens = bootstrap_config(no_identities=3)
The tokens
dictionary contains the raw tokens for each user, which you can distribute to your users securely.
Configuration Methods
You can configure the module in two ways:
- Direct configuration:
auth = BearerAuthDependency(config=config)
- Environment variable:
# Set the FASTAPI_BEARER_AUTHZN_CONFIG environment variable with a JSON string
auth = BearerAuthDependency(from_env=True)
Usage
- Initialize the
BearerAuthDependency
with your configuration. - Use the dependency in your FastAPI route decorators.
- The middleware will handle authentication and authorization based on the operation IDs.
Operation ID-based Authorization
This module uses FastAPI's operation IDs for fine-grained authorization. By default, FastAPI generates an operation ID for each route, which can be inspected in the OpenAPI JSON schema. You can also override these with custom operation IDs:
@app.get("/resource1")
def get_resource_1(user_id: str = Depends(auth)):
# Uses FastAPI's default operation ID
return {"message": "Access to resource 1 granted"}
@app.post("/resource2", operation_id="create_resource_2")
def create_resource_2(user_id: str = Depends(auth)):
# Uses custom operation ID
return {"message": "Resource 2 created"}
In your configuration, you can specify which operation IDs a user has permission to access:
config_dict = {
"user_id": PermissionConfig(
hashed_token="...",
user_identifier="user@example.com",
permissions=["get_resource_1", "create_resource_2"]
)
}
This allows for precise control over which operations each user can perform. You can inspect the OpenAPI JSON schema to see the operation IDs for each route.
Testing
Run the tests using pytest
:
pytest tests/
License
This project is licensed under the MIT License.
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
Built Distribution
Hashes for fastapi_bearer_authzn-0.2.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | d776dcc0cc27b3596548dd237b9abfd0ca83b1a0a5a6c136120dcbd32a6132c4 |
|
MD5 | c805cce23b5bdeb5fe530042af24a1d3 |
|
BLAKE2b-256 | 320780b183c610ed6fca1f7b335619549043f1382250dc1f4e268559492266d7 |
Hashes for fastapi_bearer_authzn-0.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 031024083a0a34c76454618a21a4ac55486bc0b9c3dc32ec2d0458e279009d12 |
|
MD5 | d8b7eeab4f42835f7f086cb3afa2bc17 |
|
BLAKE2b-256 | 2fc7401a1c2294987f906c009121771193eeb1de9dd0031d426b310c9e63e42a |