# 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
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)
```bash
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:
```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": "https://impalah.github.io/auth-middleware/",
"name": "auth-middleware",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "auth, middleware, fastapi, starlette",
"author": "impalah",
"author_email": "impalah@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/82/37/bf2fe5afef7cf692c8d050c3901019bbc1729a8c16889c71205faf6f9bc2/auth_middleware-0.2.2.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\napp: FastAPI = FastAPI()\n\n# Step 4: Add Middleware with a Cognito auth Provider\napp.add_middleware(JwtAuthMiddleware, auth_provider=CognitoProvider())\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\nThen set the environment variables (or your .env file)\n\n```bash\nAWS_COGNITO_USER_POOL_ID=your_cognito_user_pool_id\nAWS_COGNITO_USER_POOL_REGION=your_cognito_user_pool_region\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.2",
"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",
" middleware",
" fastapi",
" starlette"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "20ffbbca04d29f15662a672e486c859f22f84bb4beccca559f60c5c1966f0fa2",
"md5": "4796ba64cc9b422d6c4ba053fb35299a",
"sha256": "c13d1c693c991c4fa3705cebc821d7cb6c5de184d2f5879ab7c98c47496339b7"
},
"downloads": -1,
"filename": "auth_middleware-0.2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "4796ba64cc9b422d6c4ba053fb35299a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 36389,
"upload_time": "2024-12-31T18:19:10",
"upload_time_iso_8601": "2024-12-31T18:19:10.155949Z",
"url": "https://files.pythonhosted.org/packages/20/ff/bbca04d29f15662a672e486c859f22f84bb4beccca559f60c5c1966f0fa2/auth_middleware-0.2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "8237bf2fe5afef7cf692c8d050c3901019bbc1729a8c16889c71205faf6f9bc2",
"md5": "1372b7818cb406943b3f3d60f2128ab0",
"sha256": "d5e5350c7a593ebd47c8e8ad5e12f4ae0f99af679ad986ae314649683bbaa65a"
},
"downloads": -1,
"filename": "auth_middleware-0.2.2.tar.gz",
"has_sig": false,
"md5_digest": "1372b7818cb406943b3f3d60f2128ab0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 20318,
"upload_time": "2024-12-31T18:19:11",
"upload_time_iso_8601": "2024-12-31T18:19:11.334309Z",
"url": "https://files.pythonhosted.org/packages/82/37/bf2fe5afef7cf692c8d050c3901019bbc1729a8c16889c71205faf6f9bc2/auth_middleware-0.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-31 18:19:11",
"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"
}