Skip to main content

fastapi-authlib

fastapi-authlib provides easy integration between FastAPI and openid connection in your application. Provides the initialization and dependencies of oidc, aiming to unify authentication management and reduce the difficulty of use.

Installing

install and update using pip:

pip install fastapi-authlib

Examples

Create settings for examples, settings.py

config = {
    'database': 'sqlite+aiosqlite:////tmp/oidc_demo.db',
    'oauth_client_id': 'client_id',
    'oauth_client_secret': 'client_secret',
    'oauth_conf_url': 'conf_url',
    'secret_key': 'secret_key',
    'router_prefix': '',
}

settings.py is a simple configuration file of the use case, which mainly provides the database link, the necessary parameters used by oidc, the session authentication key and the routing prefix.

Please use your authentication server configuration to populate the parameter value prefixed with oauth. Other parameters can be modified according to the actual situation.

Create api route, api_router.py

from fastapi import APIRouter
from starlette.requests import Request

router = APIRouter()


@router.get('/index')
async def index(
        *,
        request: Request,
):
    """
    User
    """
    user_info = request.state.user
    return {'name': user_info.get('user_name')}

For authenticated api, you can use request.state.user to get the current user.

Create oidc demo entry, main.py

"""main"""
import uvicorn
from fastapi import Depends, FastAPI
from fastapi_sa.database import db
from fastapi_sa.middleware import DBSessionMiddleware

from fastapi_authlib.oidc import OIDCClient
from fastapi_authlib.utils.auth_dependency import check_auth_depends
from api_router import index
from .settings import config


class OIDCDemo:
    """OIDCDemo"""

    def __init__(self, settings: dict):
        self.settings = settings
        self.router_prefix = self.settings.get('router_prefix')

    def run(self):
        """Run"""
        # Early environment initialization
        app = FastAPI(title='FastAPIOIDCSupportDemo', version='0.1.0')
        db.init(self.settings.get('database'))

        # Oidc environment initialization
        client = OIDCClient(
            app=app,
            **config
        )
        # If you only init app, you should use init_app() instead
        client.init_oidc()

        # Customize the environment initialization
        # add dependencies to the interface that needs to be authenticated
        app.include_router(
            index.router,
            tags=['index'],
            prefix=config.get('router_prefix'),
            dependencies=[Depends(check_auth_depends)]
        )
        app.add_middleware(DBSessionMiddleware)
        return app


if __name__ == '__main__':
    client_app = OIDCDemo(config).run()
    uvicorn.run(client_app, host="0.0.0.0", port=8001)

Use Step

  • Create app and init db
  • Init the environment of oidc, If you don't want to do data migration, you should use init_app method. Usually database migration and oidc initialization are performed together
  • Register routing and other middleware, the DBSessionMiddleware is required
  • Start a fastapi server with uvicorn or other

Other

Provide the following apis

  • /login
  • /auth
  • /logout
  • /users

Based on

Develop

You may need to read the develop document to use SRC Layout in your IDE.

Metadata

Release files for fastapi-authlib 0.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-authlib 0.0.4
File Size Uploaded Provenance Actions
fastapi_authlib-0.0.4.tar.gz 20.0 kB Without provenance Details for fastapi_authlib-0.0.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-authlib 0.0.4
File Interpreter ABI Platform Actions
fastapi_authlib-0.0.4-py3-none-any.whl Python 3 none any Details for fastapi_authlib-0.0.4-py3-none-any.whl

Total release size: 48.9 kB

Release files / fastapi_authlib-0.0.4.tar.gz

Download URL fastapi_authlib-0.0.4.tar.gz
Size 20.0 kB
Tags Source
SHA-256 checksum
How to use checksums
40b0f2ebe96436a7d85d8fab080a90e1edac92a9fda7530b841558f302825ad7
BLAKE2b-256 checksum
How to use checksums
cc8311c517b5a73f00cadac965ac9651cb609f5e9a52f86bba009fc3fad139db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.10.7 Windows/10

Release files / fastapi_authlib-0.0.4-py3-none-any.whl

Download URL fastapi_authlib-0.0.4-py3-none-any.whl
Size 28.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dfaca507cc4fa08dd2d6a3e9236dbedaa6a2566358fee98fdb77528aed497d65
BLAKE2b-256 checksum
How to use checksums
d3d69c31916a35923710d3624766a77fdc5915a0934f1a217c7c6d6f0fd56f22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.10.7 Windows/10

Security for fastapi-authlib 0.0.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page