Code Monkey home page Code Monkey logo

fastapi-azure-auth's Introduction


FastAPI-Azure-Auth

Azure AD Authentication for FastAPI apps made easy.

Python version FastAPI Version Package version
Codecov Pre-commit Black mypy isort

๐Ÿš€ 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!

๐Ÿ“š Resources

The documentation contains a full tutorial on how to configure Azure AD and FastAPI for both single- and multi-tenant applications. 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 | Documentation | GitHub

โšก 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.

1. Install this library:

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:

# 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 your SingleTenantAzureAuthorizationCodeBearer or MultiTenantAzureAuthorizationCodeBearer.

# 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:

# 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.

5. Configure dependencies

Add azure_scheme as a dependency for your views/routers, using either Security() or Depends().

# 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.

# 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

The user can select which scopes to authenticate with, based on your configuration. scopes

fastapi-azure-auth's People

Contributors

bkmetzler avatar bmoore avatar bmooreatliberty avatar daniwk avatar dependabot[bot] avatar h3rmanj avatar jonasks avatar manupatel007 avatar orcharddweller avatar piotrgredowski avatar ravaszf avatar robteeuwen avatar sondrelg avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.