# 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
- HTTP Verb based authorization, using the `HTTP_VERB:<VERB_NAME>` format
- Configurable via environment variables or direct configuration
- Secure token generation and validation
## Installation
```bash
uv add fastapi-bearer-authzn
```
## Quick Start
```python
from fastapi import FastAPI, Depends
from fastapi_bearer_authzn import BearerAuthDependency
# Initialize the auth dependency, with the config coming from an environment variable
auth = BearerAuthDependency(from_env=True)
app = FastAPI()
@app.get("/protected")
def protected_route(user_id: str = Depends(auth)):
return {"message": "Access granted", "user_id": user_id}
```
## Configuration
Generate a configuration file using the included CLI:
```
uvx fastapi-bearer-authzn bootstrap_config -o env -n 1 # for easy environment variable usage
FASTAPI_BEARER_AUTHZN_CONFIG='{"224848fe-45df-4173-bc8c-535442611311":{"hashed_token":"ec274bd79a868d17884897455fbbb29c65f3ca076a58c3de8b2121f407a5184518013c7b38cebbffe00c4aabfa03d3dbbbc5df1ddbd206aa94936930c14e3706","user_identifier":"user_a3e7a662-764d-4afe-b84d-98bc10efccbe@example.com","permissions":["*"]}}'
Generated tokens:
224848fe-45df-4173-bc8c-535442611311: fastapi_bearer_authzn_224848fe-45df-4173-bc8c-535442611311_JZy73nSZdvtLYIO1C0o1Rv3dyemqpEeG0eGE_AIqwxs
```
## Usage
1. Initialize the `BearerAuthDependency` with your configuration.
2. Use the dependency in your FastAPI route decorators.
3. The middleware will handle authentication and authorization based on the operation IDs and HTTP verbs.
## Operation ID-based and HTTP Verb-based Authorization
This module uses FastAPI's operation IDs and HTTP verbs 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.
Given this FastAPI app:
```python
@app.get("/resource1")
def get_resource_1(user_id: str = Depends(auth)):
# Uses FastAPI's default operation ID, obtain it from the OpenAPI JSON schema, and use it in the config
return {"message": "Access to resource 1 granted"}
@app.post("/resource2", operation_id="create_resource_2")
def create_resource_2(user_id: str = Depends(auth)):
# Even better: Use a custom operation ID, then simply reference "create_resource_2" in the config to grant access to this route
return {"message": "Resource 2 created"}
```
An exemplary config may look as follows:
```jsonc
{
"e2403b7b-822b-4a0c-8586-85adb672169c": {
"hashed_token": "e725c175f719caae1dcc0f0421663402c90f551790f869fcef786fb217a8084e20dfbef7ac47309926919a659da9db4f0cb1062dec578bc907bc18991bbb390f",
"user_identifier": "Used by microservice X", # arbitrary string, for you to identify the user/service
"permissions": [
"HTTP_VERB:GET",
"create_resource_2"
]
}
}
```
This config grants access to all paths via `GET` and only to the `create_resource_2` path via `POST`.
## Testing
Run the tests using `pytest`:
```bash
uv run pytest tests -vv
```
## License
This project is licensed under the MIT License.
## Publish to PyPI
For the time being, you can publish the package to pypi manually.
```bash
uv build
uvx twine upload dist/* # or `uvx twine upload --repository testpypi dist/*` for testpypi
```
You will be prompted for a PyPI API token.
Raw data
{
"_id": null,
"home_page": null,
"name": "fastapi-bearer-authzn",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "authentication, authn, authorization, authz, bearer, fastapi, middleware, token",
"author": "SysEleven GmbH",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/4f/7f/7daa68f3b147c6f226877449a3527ecc10d5c91133879741890eb015e901/fastapi_bearer_authzn-0.3.0.tar.gz",
"platform": null,
"description": "# FastAPI Bearer Authorization\n\nA robust bearer token authentication and authorization middleware for FastAPI applications.\n\n> [!WARNING] \n> This project is in early development and may not be suitable for production use.\n\n## Features\n\n- Easy-to-use bearer token authentication\n- Fine-grained permission-based authorization using unique operation IDs\n- HTTP Verb based authorization, using the `HTTP_VERB:<VERB_NAME>` format\n- Configurable via environment variables or direct configuration\n- Secure token generation and validation\n\n## Installation\n\n```bash\nuv add fastapi-bearer-authzn\n```\n\n## Quick Start\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom fastapi_bearer_authzn import BearerAuthDependency\n\n# Initialize the auth dependency, with the config coming from an environment variable\nauth = BearerAuthDependency(from_env=True)\n\napp = FastAPI()\n\n@app.get(\"/protected\")\ndef protected_route(user_id: str = Depends(auth)):\n return {\"message\": \"Access granted\", \"user_id\": user_id}\n```\n\n## Configuration\n\nGenerate a configuration file using the included CLI:\n\n```\nuvx fastapi-bearer-authzn bootstrap_config -o env -n 1 # for easy environment variable usage\n\nFASTAPI_BEARER_AUTHZN_CONFIG='{\"224848fe-45df-4173-bc8c-535442611311\":{\"hashed_token\":\"ec274bd79a868d17884897455fbbb29c65f3ca076a58c3de8b2121f407a5184518013c7b38cebbffe00c4aabfa03d3dbbbc5df1ddbd206aa94936930c14e3706\",\"user_identifier\":\"user_a3e7a662-764d-4afe-b84d-98bc10efccbe@example.com\",\"permissions\":[\"*\"]}}'\n\nGenerated tokens:\n224848fe-45df-4173-bc8c-535442611311: fastapi_bearer_authzn_224848fe-45df-4173-bc8c-535442611311_JZy73nSZdvtLYIO1C0o1Rv3dyemqpEeG0eGE_AIqwxs\n```\n\n## Usage\n\n1. Initialize the `BearerAuthDependency` with your configuration.\n2. Use the dependency in your FastAPI route decorators.\n3. The middleware will handle authentication and authorization based on the operation IDs and HTTP verbs.\n\n## Operation ID-based and HTTP Verb-based Authorization\n\nThis module uses FastAPI's operation IDs and HTTP verbs 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.\n\nGiven this FastAPI app:\n\n```python\n@app.get(\"/resource1\")\ndef get_resource_1(user_id: str = Depends(auth)):\n # Uses FastAPI's default operation ID, obtain it from the OpenAPI JSON schema, and use it in the config\n return {\"message\": \"Access to resource 1 granted\"}\n\n@app.post(\"/resource2\", operation_id=\"create_resource_2\")\ndef create_resource_2(user_id: str = Depends(auth)):\n # Even better: Use a custom operation ID, then simply reference \"create_resource_2\" in the config to grant access to this route\n return {\"message\": \"Resource 2 created\"}\n```\n\nAn exemplary config may look as follows:\n\n```jsonc\n{\n \"e2403b7b-822b-4a0c-8586-85adb672169c\": {\n \"hashed_token\": \"e725c175f719caae1dcc0f0421663402c90f551790f869fcef786fb217a8084e20dfbef7ac47309926919a659da9db4f0cb1062dec578bc907bc18991bbb390f\",\n \"user_identifier\": \"Used by microservice X\", # arbitrary string, for you to identify the user/service\n \"permissions\": [\n \"HTTP_VERB:GET\",\n \"create_resource_2\"\n ]\n }\n}\n```\n\nThis config grants access to all paths via `GET` and only to the `create_resource_2` path via `POST`.\n\n## Testing\n\nRun the tests using `pytest`:\n\n```bash\nuv run pytest tests -vv\n```\n\n## License\n\nThis project is licensed under the MIT License.\n\n## Publish to PyPI\n\nFor the time being, you can publish the package to pypi manually.\n\n```bash\nuv build\nuvx twine upload dist/* # or `uvx twine upload --repository testpypi dist/*` for testpypi\n```\n\nYou will be prompted for a PyPI API token.\n",
"bugtrack_url": null,
"license": null,
"summary": "A robust bearer token authentication and authorization middleware for FastAPI applications.",
"version": "0.3.0",
"project_urls": {
"Changelog": "https://github.com/syseleven/fastapi-bearer-authzn/blob/main/CHANGELOG.md",
"Homepage": "https://www.syseleven.de/",
"Repository": "https://github.com/syseleven/fastapi-bearer-authzn"
},
"split_keywords": [
"authentication",
" authn",
" authorization",
" authz",
" bearer",
" fastapi",
" middleware",
" token"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "964b5aa192a58e42575eefba96213b2571faa6e332580602bbf7b032fb53ddc0",
"md5": "b6d2cf4d12ee6cf06027181668036316",
"sha256": "3227af0588a98d23b440fdfaf5636b18a54f26fe76cb6095e8833b2a7ade026b"
},
"downloads": -1,
"filename": "fastapi_bearer_authzn-0.3.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "b6d2cf4d12ee6cf06027181668036316",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 7875,
"upload_time": "2024-09-09T13:13:45",
"upload_time_iso_8601": "2024-09-09T13:13:45.460597Z",
"url": "https://files.pythonhosted.org/packages/96/4b/5aa192a58e42575eefba96213b2571faa6e332580602bbf7b032fb53ddc0/fastapi_bearer_authzn-0.3.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "4f7f7daa68f3b147c6f226877449a3527ecc10d5c91133879741890eb015e901",
"md5": "4dba087b17785e0f281ea0d59e3ce368",
"sha256": "617f5b198d52fab0beba320e07fab176fd1f81b3d1de581cd4242d5e9032164b"
},
"downloads": -1,
"filename": "fastapi_bearer_authzn-0.3.0.tar.gz",
"has_sig": false,
"md5_digest": "4dba087b17785e0f281ea0d59e3ce368",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 24113,
"upload_time": "2024-09-09T13:13:47",
"upload_time_iso_8601": "2024-09-09T13:13:47.638348Z",
"url": "https://files.pythonhosted.org/packages/4f/7f/7daa68f3b147c6f226877449a3527ecc10d5c91133879741890eb015e901/fastapi_bearer_authzn-0.3.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-09 13:13:47",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "syseleven",
"github_project": "fastapi-bearer-authzn",
"github_not_found": true,
"lcname": "fastapi-bearer-authzn"
}