auth-middleware


Nameauth-middleware JSON
Version 0.1.18 PyPI version JSON
download
home_pagehttps://impalah.github.io/auth-middleware/
SummaryAsync Auth Middleware for FastAPI/Starlette
upload_time2024-05-11 08:44:52
maintainerNone
docs_urlNone
authorimpalah
requires_python>=3.10
licenseMIT
keywords auth middleware fastapi starlette
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # auth-middleware

Async Auth Middleware for FastAPI/Starlette.

## Installation

Using pip:

```bash
pip install auth-middleware
```

Using poetry

```bash
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:

```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": ">=3.10",
    "maintainer_email": null,
    "keywords": "auth, middleware, fastapi, starlette",
    "author": "impalah",
    "author_email": "impalah@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/26/07/bbefc60d98dbfae8aaf6d8d0fc9bc4dd4febbb6bac70fed63a1d87da7716/auth_middleware-0.1.18.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 auth-middleware\n```\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\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\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\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\n## Authentication providers\n\n### Amazon Cognito\n\nTODO\n\n### Azure Entra ID\n\nTODO\n\n\n### Google Idp\n\nTODO\n\n\n## Custom auth provider\n\nTODO\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Async Auth Middleware for FastAPI/Starlette",
    "version": "0.1.18",
    "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": "7040a018c8dd84ed819a981e1b806b046d02f0a35a3d089dd716e700579b33c5",
                "md5": "cec026532e249617d936773350747ffd",
                "sha256": "5f3864dcdbef94cc01b15b32ad91c06ffbaf7e5068326a4469e98452f21bc9a4"
            },
            "downloads": -1,
            "filename": "auth_middleware-0.1.18-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "cec026532e249617d936773350747ffd",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 22550,
            "upload_time": "2024-05-11T08:44:50",
            "upload_time_iso_8601": "2024-05-11T08:44:50.964352Z",
            "url": "https://files.pythonhosted.org/packages/70/40/a018c8dd84ed819a981e1b806b046d02f0a35a3d089dd716e700579b33c5/auth_middleware-0.1.18-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2607bbefc60d98dbfae8aaf6d8d0fc9bc4dd4febbb6bac70fed63a1d87da7716",
                "md5": "d28d65dbeca1be4b72baf1eecb91df4c",
                "sha256": "dc8efab2236b371990d31dc0ca2893d236145690e46c3d4f14165fe33245ff8d"
            },
            "downloads": -1,
            "filename": "auth_middleware-0.1.18.tar.gz",
            "has_sig": false,
            "md5_digest": "d28d65dbeca1be4b72baf1eecb91df4c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 13555,
            "upload_time": "2024-05-11T08:44:52",
            "upload_time_iso_8601": "2024-05-11T08:44:52.314648Z",
            "url": "https://files.pythonhosted.org/packages/26/07/bbefc60d98dbfae8aaf6d8d0fc9bc4dd4febbb6bac70fed63a1d87da7716/auth_middleware-0.1.18.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-11 08:44:52",
    "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"
}
        
Elapsed time: 0.26725s