Skip to main content

A fastapi authlib authentication library

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_authlib-0.0.4.tar.gz (20.0 kB view details)

Uploaded Source

Built Distribution

fastapi_authlib-0.0.4-py3-none-any.whl (28.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_authlib-0.0.4.tar.gz.

File metadata

  • Download URL: fastapi_authlib-0.0.4.tar.gz
  • Upload date:
  • Size: 20.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.10.7 Windows/10

File hashes

Hashes for fastapi_authlib-0.0.4.tar.gz
Algorithm Hash digest
SHA256 40b0f2ebe96436a7d85d8fab080a90e1edac92a9fda7530b841558f302825ad7
MD5 8b0f82c022de3dc49a9a5246909237e0
BLAKE2b-256 cc8311c517b5a73f00cadac965ac9651cb609f5e9a52f86bba009fc3fad139db

See more details on using hashes here.

File details

Details for the file fastapi_authlib-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: fastapi_authlib-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 28.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.10.7 Windows/10

File hashes

Hashes for fastapi_authlib-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 dfaca507cc4fa08dd2d6a3e9236dbedaa6a2566358fee98fdb77528aed497d65
MD5 b88621becb2caf593d91df83407f8734
BLAKE2b-256 d3d69c31916a35923710d3624766a77fdc5915a0934f1a217c7c6d6f0fd56f22

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page