# auth-middleware
Async Auth Middleware for FastAPI/Starlette.
## Installation
Using pip:
```bash
pip install auth-middleware
```
Using poetry
```bash
poetry add 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:
```python
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
# Implement group provider (if any)
from auth_middleware.providers.authz.cognito_groups_provider import (
CognitoGroupsProvider,
)
app: FastAPI = FastAPI()
# Step 4: Add Middleware with a Cognito auth Provider
auth_provider_settings: CognitoAuthzProviderSettings = CognitoAuthzProviderSettings(
user_pool_id="My Pool Id",
user_pool_region="AWS_REGION",
jwt_token_verification_disabled=true,
)
app.add_middleware(
JwtAuthMiddleware,
auth_provider=CognitoProvider(
settings=auth_provider_settings,
groups_provider=CognitoGroupsProvider,
# permissions_provider=SqlPermissionsProvider,
),
)
@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}"}
```
Call the method sending the id_token provided by Cognito:
```bash
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:
```python
require_user()
```
To check if a user has assigned a group or groups use require_groups:
```python
require_groups(["group1", "group2"])
```
## Authentication providers
### Amazon Cognito
TODO
### Azure Entra ID
TODO
### Google Idp
TODO
## Custom auth provider
TODO
Raw data
{
"_id": null,
"home_page": null,
"name": "auth-middleware",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "auth, fastapi, middleware, starlette",
"author": null,
"author_email": "impalah <impalah@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/5d/18/bc61eb33c69419c61c77877e6bc05102eb51a2323891ebc75c987c1c4536/auth_middleware-0.2.12.tar.gz",
"platform": null,
"description": "# auth-middleware\n\nAsync Auth Middleware for FastAPI/Starlette.\n\n## Installation\n\nUsing pip:\n\n```bash\npip install auth-middleware\n```\n\nUsing poetry\n\n```bash\npoetry add auth-middleware\n```\n\n## How to use it\n\nAuth Middleware follows the middleware protocol and, therefore, should be added as a middleware to your FastApi or Starlette application.\n\nThe steps, using FastAPI:\n\n```python\n\nfrom fastapi import FastAPI, Depends\n\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n\n# Step 1: import the functions to control authentication\nfrom auth_middleware.functions import require_groups, require_user\n# Step 2: import the Middleware to use\nfrom auth_middleware.jwt_auth_middleware import JwtAuthMiddleware\n# Step 3: import the auth provider\nfrom auth_middleware.providers.cognito import CognitoProvider\n# Implement group provider (if any)\nfrom auth_middleware.providers.authz.cognito_groups_provider import (\n CognitoGroupsProvider,\n)\n\n\napp: FastAPI = FastAPI()\n\n# Step 4: Add Middleware with a Cognito auth Provider\nauth_provider_settings: CognitoAuthzProviderSettings = CognitoAuthzProviderSettings(\n user_pool_id=\"My Pool Id\",\n user_pool_region=\"AWS_REGION\",\n jwt_token_verification_disabled=true,\n)\n\napp.add_middleware(\n JwtAuthMiddleware,\n auth_provider=CognitoProvider(\n settings=auth_provider_settings,\n groups_provider=CognitoGroupsProvider,\n # permissions_provider=SqlPermissionsProvider,\n ),\n)\n\n\n@app.get(\"/\",\n dependencies=[\n # Step 5: add the authorization dependencies you want: require_user or requiere_groups\n # Depends(require_groups([\"customer\", \"administrator\"])),\n Depends(require_user()),\n ],)\nasync def root(request: Request):\n # Step 6: user information will be available in the request.state.current_user object\n return {\"message\": f\"Hello {request.state.current_user.name}\"}\n\n```\n\nCall the method sending the id_token provided by Cognito:\n\n```bash\ncurl -X GET http://localhost:8000/ -H \"Authorization: Bearer MY_ID_TOKEN\"\n```\n\n## Middleware configuration\n\nThe middleware configuration is done by environment variables (or using and .env file if your project uses python-dotenv).\n\nThe main variables are shwon in the table below:\n\n| Name | Description | Values | Default |\n| ------------------------------------------- | --------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------- |\n| AUTH_MIDDLEWARE_LOG_LEVEL | Log level for the application | DEBUG, INFO, WARNING, ERROR, CRITICAL | INFO |\n| AUTH_MIDDLEWARE_LOG_FORMAT | Log format | See python logger documentation | %(log_color)s%(levelname)-9s%(reset)s %(asctime)s %(name)s %(message)s |\n| AUTH_MIDDLEWARE_LOGGER_NAME | Auth middleware logger name | A string | auth_middleware |\n| AUTH_MIDDLEWARE_DISABLED | Auth middleware enabled/disabled | false, true | false |\n| AUTH_MIDDLEWARE_JWKS_CACHE_INTERVAL_MINUTES | JWKS keys file refreshing interval | An integer value | 20 |\n| AUTH_MIDDLEWARE_JWKS_CACHE_USAGES | JWKS keys refreshing interval (counter) | An integer value | 1000 |\n\n## The User property\n\nAfter authentication the Request object contains ifnormation about the current user in the state.current_user variable.\n\nThe table below shows the properties of the user object.\n\n| Property | Description |\n| -------- | ----------------------------------------------------- |\n| id | Id of the user in the identity provider |\n| name | User name (or id if not defined) |\n| email | User email (if any) |\n| groups | Array of user groups as sent by the identity provider |\n\n## Control authentication and authorization\n\nThere are two utility functions to control the authentication and authorization. These functions return an HttpException if the auth/authn fails.\n\nThe functions can be invoked directly or can be used as a dependency in frameworks as FastAPI.\n\nTo check if a user is logged in use require_user:\n\n```python\nrequire_user()\n```\n\nTo check if a user has assigned a group or groups use require_groups:\n\n```python\nrequire_groups([\"group1\", \"group2\"])\n```\n\n## Authentication providers\n\n### Amazon Cognito\n\nTODO\n\n### Azure Entra ID\n\nTODO\n\n### Google Idp\n\nTODO\n\n## Custom auth provider\n\nTODO\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Async Auth Middleware for FastAPI/Starlette",
"version": "0.2.12",
"project_urls": {
"Documentation": "https://impalah.github.io/auth-middleware/",
"Homepage": "https://impalah.github.io/auth-middleware/",
"Repository": "https://github.com/impalah/auth-middleware",
"Source": "https://github.com/impalah/auth-middleware"
},
"split_keywords": [
"auth",
" fastapi",
" middleware",
" starlette"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "42155fafeb3f4fe85e6835ab7c01d5685e940e79226dbf8b713dd959f6573f2f",
"md5": "655498560768bd38d58bb952882af9ea",
"sha256": "b5a7db416d13b1e2fc73ccd151f3f130b24a9a2ec620dadf373c27f18f0c99f5"
},
"downloads": -1,
"filename": "auth_middleware-0.2.12-py3-none-any.whl",
"has_sig": false,
"md5_digest": "655498560768bd38d58bb952882af9ea",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 36569,
"upload_time": "2025-08-07T16:45:52",
"upload_time_iso_8601": "2025-08-07T16:45:52.876194Z",
"url": "https://files.pythonhosted.org/packages/42/15/5fafeb3f4fe85e6835ab7c01d5685e940e79226dbf8b713dd959f6573f2f/auth_middleware-0.2.12-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "5d18bc61eb33c69419c61c77877e6bc05102eb51a2323891ebc75c987c1c4536",
"md5": "624a170890207afbe8dc4bc46dbd5ec0",
"sha256": "223768615b0b27326dece29e666d4be5d45ac1c379e38cd062435cdca1862b83"
},
"downloads": -1,
"filename": "auth_middleware-0.2.12.tar.gz",
"has_sig": false,
"md5_digest": "624a170890207afbe8dc4bc46dbd5ec0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 8583159,
"upload_time": "2025-08-07T16:45:53",
"upload_time_iso_8601": "2025-08-07T16:45:53.975161Z",
"url": "https://files.pythonhosted.org/packages/5d/18/bc61eb33c69419c61c77877e6bc05102eb51a2323891ebc75c987c1c4536/auth_middleware-0.2.12.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-07 16:45:53",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "impalah",
"github_project": "auth-middleware",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "auth-middleware"
}