fastapi-azure-auth


Namefastapi-azure-auth JSON
Version 4.3.1 PyPI version JSON
download
home_pagehttps://github.com/intility/fastapi-azure-auth
SummaryEasy and secure implementation of Azure AD for your FastAPI APIs
upload_time2024-03-04 15:48:52
maintainer
docs_urlNone
authorJonas Krüger Svensson
requires_python>=3.8,<4.0
license
keywords ad async asyncio authentication azure azure ad azuread fastapi multi tenant oauth2 oidc security single tenant starlette trio
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h1 align="center">
  <img margin="0 10px 0 0" src="https://avatars.githubusercontent.com/u/35199565" width="124px"/>
  <img margin="0 10px 0 0" src="https://raw.githubusercontent.com/Intility/fastapi-azure-auth/main/docs/static/img/global/fastad.png" width="124px"/><br/>
  FastAPI-Azure-Auth
</h1>

<p align="center">
    <em>Azure AD Authentication for FastAPI apps made easy.</em>
</p>
<p align="center">
    <!-- Line 1 -->
    <a href="https://python.org">
        <img src="https://img.shields.io/badge/python-v3.8+-blue.svg?logo=python&logoColor=white&label=python" alt="Python version">
    </a>
    <a href="https://fastapi.tiangolo.com/">
        <img src="https://img.shields.io/badge/FastAPI-0.68.0+%20-blue.svg?logo=fastapi&logoColor=white&label=fastapi" alt="FastAPI Version">
    </a>
    <a href="https://pypi.org/pypi/fastapi-azure-auth">
        <img src="https://img.shields.io/pypi/v/fastapi-azure-auth.svg?logo=pypi&logoColor=white&label=pypi" alt="Package version">
    </a>
    <!-- Line 2 -->
    <br/>
    <a href="https://codecov.io/gh/intility/fastapi-azure-auth">
        <img src="https://codecov.io/gh/intility/fastapi-azure-auth/branch/main/graph/badge.svg?token=BTFGII4GYR" alt="Codecov">
    </a>
    <a href="https://github.com/pre-commit/pre-commit">
        <img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white" alt="Pre-commit">
    </a>
    <a href="https://github.com/psf/black">
        <img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Black">
    </a>
    <a href="http://mypy-lang.org">
        <img src="http://www.mypy-lang.org/static/mypy_badge.svg" alt="mypy">
    </a>
    <a href="https://pycqa.github.io/isort/">
        <img src="https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336" alt="isort">
    </a>
    <!-- Line 3 -->
    <br/>
    <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/single-and-multi-tenant-apps">
        <img src="https://img.shields.io/badge/Single--tenant-Supported-blue?logo=Microsoft%20Azure&logoColor=white">
    </a>
    <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/single-and-multi-tenant-apps">
        <img src="https://img.shields.io/badge/Multi--tenant-Supported-blue?logo=Microsoft%20Azure&logoColor=white">
    </a>
</p>


## 🚀 Description

> FastAPI is a modern, fast (high-performance), web framework for building APIs with Python, based on standard Python type hints.

At Intility we use FastAPI for both internal (single-tenant) and customer-facing (multi-tenant) APIs. This package enables our developers (and you 😊) to create features without worrying about authentication and authorization.

Also, [we're hiring!](https://intility.no/en/career/)

## 📚 Resources

The [documentation](https://intility.github.io/fastapi-azure-auth/) contains a full tutorial on how to configure Azure AD
and FastAPI for single- and multi-tenant applications as well as B2C apps. It includes examples on how to lock down
your APIs to certain scopes, tenants, roles etc. For first time users it's strongly advised to set up your
application exactly how it's described there, and then alter it to your needs later.

[**MIT License**](https://github.com/Intility/fastapi-azure-auth/blob/main/LICENSE)
| [**Documentation**](https://intility.github.io/fastapi-azure-auth/)
| [**GitHub**](https://github.com/snok/django-guid)


## ⚡ Setup

This is a tl;dr intended to give you an idea of what this package does and how to use it.
For a more in-depth tutorial and settings reference you should read the
[documentation](https://intility.github.io/fastapi-azure-auth/).


#### 1. Install this library:
```bash
pip install fastapi-azure-auth
# or
poetry add fastapi-azure-auth
```

#### 2. Configure your FastAPI app
Include `swagger_ui_oauth2_redirect_url` and `swagger_ui_init_oauth` in your FastAPI app initialization:

```python
# file: main.py
app = FastAPI(
    ...
    swagger_ui_oauth2_redirect_url='/oauth2-redirect',
    swagger_ui_init_oauth={
        'usePkceWithAuthorizationCodeGrant': True,
        'clientId': settings.OPENAPI_CLIENT_ID,
    },
)
```

#### 3. Setup CORS
Ensure you have CORS enabled for your local environment, such as `http://localhost:8000`.

#### 4. Configure FastAPI-Azure-Auth
Configure either [`SingleTenantAzureAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/single_tenant), [`MultiTenantAzureAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/multi_tenant) or [`B2CMultiTenantAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/b2c)


```python
# file: demoproj/api/dependencies.py
from fastapi_azure_auth.auth import SingleTenantAzureAuthorizationCodeBearer

azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    tenant_id=settings.TENANT_ID,
    scopes={
        f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',
    }
)
```
or for multi-tenant applications:
```python
# file: demoproj/api/dependencies.py
from fastapi_azure_auth.auth import MultiTenantAzureAuthorizationCodeBearer

azure_scheme = MultiTenantAzureAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    scopes={
        f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',
    },
    validate_iss=False
)
```
To validate the `iss`, configure an
[`iss_callable`](https://intility.github.io/fastapi-azure-auth/multi-tenant/accept_specific_tenants_only).

#### 5. Configure dependencies

Add `azure_scheme` as a dependency for your views/routers, using either `Security()` or `Depends()`.
```python
# file: main.py
from demoproj.api.dependencies import azure_scheme

app.include_router(api_router, prefix=settings.API_V1_STR, dependencies=[Security(azure_scheme, scopes=['user_impersonation'])])
```

#### 6. Load config on startup

Optional but recommended.

```python
# file: main.py
@app.on_event('startup')
async def load_config() -> None:
    """
    Load OpenID config on startup.
    """
    await azure_scheme.openid_config.load_config()
```


## 📄 Example OpenAPI documentation
Your OpenAPI documentation will get an `Authorize` button, which can be used to authenticate.
![authorize](docs/static/img/single-and-multi-tenant/fastapi_1_authorize_button.png)

The user can select which scopes to authenticate with, based on your configuration.
![scopes](docs/static/img/single-and-multi-tenant/fastapi_3_authenticate.png)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/intility/fastapi-azure-auth",
    "name": "fastapi-azure-auth",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "ad,async,asyncio,authentication,azure,azure ad,azuread,fastapi,multi tenant,oauth2,oidc,security,single tenant,starlette,trio",
    "author": "Jonas Kr\u00fcger Svensson",
    "author_email": "jonas.svensson@intility.no",
    "download_url": "https://files.pythonhosted.org/packages/a2/89/1c6857d46c96a7799c4526090600458709bb3c6903dbb69f0addc69f68bb/fastapi_azure_auth-4.3.1.tar.gz",
    "platform": null,
    "description": "<h1 align=\"center\">\n  <img margin=\"0 10px 0 0\" src=\"https://avatars.githubusercontent.com/u/35199565\" width=\"124px\"/>\n  <img margin=\"0 10px 0 0\" src=\"https://raw.githubusercontent.com/Intility/fastapi-azure-auth/main/docs/static/img/global/fastad.png\" width=\"124px\"/><br/>\n  FastAPI-Azure-Auth\n</h1>\n\n<p align=\"center\">\n    <em>Azure AD Authentication for FastAPI apps made easy.</em>\n</p>\n<p align=\"center\">\n    <!-- Line 1 -->\n    <a href=\"https://python.org\">\n        <img src=\"https://img.shields.io/badge/python-v3.8+-blue.svg?logo=python&logoColor=white&label=python\" alt=\"Python version\">\n    </a>\n    <a href=\"https://fastapi.tiangolo.com/\">\n        <img src=\"https://img.shields.io/badge/FastAPI-0.68.0+%20-blue.svg?logo=fastapi&logoColor=white&label=fastapi\" alt=\"FastAPI Version\">\n    </a>\n    <a href=\"https://pypi.org/pypi/fastapi-azure-auth\">\n        <img src=\"https://img.shields.io/pypi/v/fastapi-azure-auth.svg?logo=pypi&logoColor=white&label=pypi\" alt=\"Package version\">\n    </a>\n    <!-- Line 2 -->\n    <br/>\n    <a href=\"https://codecov.io/gh/intility/fastapi-azure-auth\">\n        <img src=\"https://codecov.io/gh/intility/fastapi-azure-auth/branch/main/graph/badge.svg?token=BTFGII4GYR\" alt=\"Codecov\">\n    </a>\n    <a href=\"https://github.com/pre-commit/pre-commit\">\n        <img src=\"https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white\" alt=\"Pre-commit\">\n    </a>\n    <a href=\"https://github.com/psf/black\">\n        <img src=\"https://img.shields.io/badge/code%20style-black-000000.svg\" alt=\"Black\">\n    </a>\n    <a href=\"http://mypy-lang.org\">\n        <img src=\"http://www.mypy-lang.org/static/mypy_badge.svg\" alt=\"mypy\">\n    </a>\n    <a href=\"https://pycqa.github.io/isort/\">\n        <img src=\"https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336\" alt=\"isort\">\n    </a>\n    <!-- Line 3 -->\n    <br/>\n    <a href=\"https://docs.microsoft.com/en-us/azure/active-directory/develop/single-and-multi-tenant-apps\">\n        <img src=\"https://img.shields.io/badge/Single--tenant-Supported-blue?logo=Microsoft%20Azure&logoColor=white\">\n    </a>\n    <a href=\"https://docs.microsoft.com/en-us/azure/active-directory/develop/single-and-multi-tenant-apps\">\n        <img src=\"https://img.shields.io/badge/Multi--tenant-Supported-blue?logo=Microsoft%20Azure&logoColor=white\">\n    </a>\n</p>\n\n\n## \ud83d\ude80 Description\n\n> FastAPI is a modern, fast (high-performance), web framework for building APIs with Python, based on standard Python type hints.\n\nAt Intility we use FastAPI for both internal (single-tenant) and customer-facing (multi-tenant) APIs. This package enables our developers (and you \ud83d\ude0a) to create features without worrying about authentication and authorization.\n\nAlso, [we're hiring!](https://intility.no/en/career/)\n\n## \ud83d\udcda Resources\n\nThe [documentation](https://intility.github.io/fastapi-azure-auth/) contains a full tutorial on how to configure Azure AD\nand FastAPI for single- and multi-tenant applications as well as B2C apps. It includes examples on how to lock down\nyour APIs to certain scopes, tenants, roles etc. For first time users it's strongly advised to set up your\napplication exactly how it's described there, and then alter it to your needs later.\n\n[**MIT License**](https://github.com/Intility/fastapi-azure-auth/blob/main/LICENSE)\n| [**Documentation**](https://intility.github.io/fastapi-azure-auth/)\n| [**GitHub**](https://github.com/snok/django-guid)\n\n\n## \u26a1 Setup\n\nThis is a tl;dr intended to give you an idea of what this package does and how to use it.\nFor a more in-depth tutorial and settings reference you should read the\n[documentation](https://intility.github.io/fastapi-azure-auth/).\n\n\n#### 1. Install this library:\n```bash\npip install fastapi-azure-auth\n# or\npoetry add fastapi-azure-auth\n```\n\n#### 2. Configure your FastAPI app\nInclude `swagger_ui_oauth2_redirect_url` and `swagger_ui_init_oauth` in your FastAPI app initialization:\n\n```python\n# file: main.py\napp = FastAPI(\n    ...\n    swagger_ui_oauth2_redirect_url='/oauth2-redirect',\n    swagger_ui_init_oauth={\n        'usePkceWithAuthorizationCodeGrant': True,\n        'clientId': settings.OPENAPI_CLIENT_ID,\n    },\n)\n```\n\n#### 3. Setup CORS\nEnsure you have CORS enabled for your local environment, such as `http://localhost:8000`.\n\n#### 4. Configure FastAPI-Azure-Auth\nConfigure either [`SingleTenantAzureAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/single_tenant), [`MultiTenantAzureAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/multi_tenant) or [`B2CMultiTenantAuthorizationCodeBearer`](https://intility.github.io/fastapi-azure-auth/settings/b2c)\n\n\n```python\n# file: demoproj/api/dependencies.py\nfrom fastapi_azure_auth.auth import SingleTenantAzureAuthorizationCodeBearer\n\nazure_scheme = SingleTenantAzureAuthorizationCodeBearer(\n    app_client_id=settings.APP_CLIENT_ID,\n    tenant_id=settings.TENANT_ID,\n    scopes={\n        f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',\n    }\n)\n```\nor for multi-tenant applications:\n```python\n# file: demoproj/api/dependencies.py\nfrom fastapi_azure_auth.auth import MultiTenantAzureAuthorizationCodeBearer\n\nazure_scheme = MultiTenantAzureAuthorizationCodeBearer(\n    app_client_id=settings.APP_CLIENT_ID,\n    scopes={\n        f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',\n    },\n    validate_iss=False\n)\n```\nTo validate the `iss`, configure an\n[`iss_callable`](https://intility.github.io/fastapi-azure-auth/multi-tenant/accept_specific_tenants_only).\n\n#### 5. Configure dependencies\n\nAdd `azure_scheme` as a dependency for your views/routers, using either `Security()` or `Depends()`.\n```python\n# file: main.py\nfrom demoproj.api.dependencies import azure_scheme\n\napp.include_router(api_router, prefix=settings.API_V1_STR, dependencies=[Security(azure_scheme, scopes=['user_impersonation'])])\n```\n\n#### 6. Load config on startup\n\nOptional but recommended.\n\n```python\n# file: main.py\n@app.on_event('startup')\nasync def load_config() -> None:\n    \"\"\"\n    Load OpenID config on startup.\n    \"\"\"\n    await azure_scheme.openid_config.load_config()\n```\n\n\n## \ud83d\udcc4 Example OpenAPI documentation\nYour OpenAPI documentation will get an `Authorize` button, which can be used to authenticate.\n![authorize](docs/static/img/single-and-multi-tenant/fastapi_1_authorize_button.png)\n\nThe user can select which scopes to authenticate with, based on your configuration.\n![scopes](docs/static/img/single-and-multi-tenant/fastapi_3_authenticate.png)\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Easy and secure implementation of Azure AD for your FastAPI APIs",
    "version": "4.3.1",
    "project_urls": {
        "Documentation": "https://github.com/intility/fastapi-azure-auth",
        "Homepage": "https://github.com/intility/fastapi-azure-auth",
        "Repository": "https://github.com/intility/fastapi-azure-auth"
    },
    "split_keywords": [
        "ad",
        "async",
        "asyncio",
        "authentication",
        "azure",
        "azure ad",
        "azuread",
        "fastapi",
        "multi tenant",
        "oauth2",
        "oidc",
        "security",
        "single tenant",
        "starlette",
        "trio"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "79c584332091d85791d0fbab7d2bc3f55d5121d42d22dff984886354963e26a2",
                "md5": "ceac95cc001713539d7e57c8a12f0dd3",
                "sha256": "10daf66ed49609a35a6acb54632502b3293eb0fe501b568244d741dd40426e0e"
            },
            "downloads": -1,
            "filename": "fastapi_azure_auth-4.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ceac95cc001713539d7e57c8a12f0dd3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 13761,
            "upload_time": "2024-03-04T15:48:50",
            "upload_time_iso_8601": "2024-03-04T15:48:50.877569Z",
            "url": "https://files.pythonhosted.org/packages/79/c5/84332091d85791d0fbab7d2bc3f55d5121d42d22dff984886354963e26a2/fastapi_azure_auth-4.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a2891c6857d46c96a7799c4526090600458709bb3c6903dbb69f0addc69f68bb",
                "md5": "4ef397122cfe9a48b2034e9b7bd2a99d",
                "sha256": "aaa6c61909e53cca3d73d9ee84e71adc680cd0a7bd8f51578d626706a6aa91b3"
            },
            "downloads": -1,
            "filename": "fastapi_azure_auth-4.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4ef397122cfe9a48b2034e9b7bd2a99d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 13805,
            "upload_time": "2024-03-04T15:48:52",
            "upload_time_iso_8601": "2024-03-04T15:48:52.630842Z",
            "url": "https://files.pythonhosted.org/packages/a2/89/1c6857d46c96a7799c4526090600458709bb3c6903dbb69f0addc69f68bb/fastapi_azure_auth-4.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-04 15:48:52",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "intility",
    "github_project": "fastapi-azure-auth",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-azure-auth"
}
        
Elapsed time: 0.19801s