Custom Auth provider

You can implement custom auth provider by inheriting from class below and implementing necessary methods.

class horizon.backend.providers.auth.AuthProvider

Basic class for all Auth providers.

Constructor is called by FastAPI, and can use Dependency injection mechanism. See setup for more details.

Methods

get_current_user(access_token)

This method should return currently logged in user.

get_token([grant_type, login, password, ...])

This method should perform authentication and return JWT token.

setup(app)

This method is called by horizon.backend.application_factory.

abstractmethod classmethod setup(app: FastAPI) FastAPI

This method is called by horizon.backend.application_factory.

Here you should add dependency overrides for auth provider, and return new app object.

Examples

from fastapi import FastAPI
from my_awesome_auth_provider.settings import MyAwesomeAuthProviderSettings
from horizon.backend.dependencies import Stub

class MyAwesomeAuthProvider(AuthProvider):
    def setup(app):
        app.dependency_overrides[AuthProvider] = MyAwesomeAuthProvider

        # `settings_object_factory` returns MyAwesomeAuthProviderSettings object
        app.dependency_overrides[MyAwesomeAuthProviderSettings] = settings_object_factory
        return app

    def __init__(
        self,
        settings: Annotated[MyAwesomeAuthProviderSettings, Depends(Stub(MyAwesomeAuthProviderSettings))],
    ):
        # settings object is set automatically by FastAPI's dependency_overrides
        self.settings = settings
abstractmethod async get_current_user(access_token: str) User

This method should return currently logged in user.

Parameters:
access_tokenstr

JWT token got from Authorization: Bearer <token> header.

Returns:
horizon.backend.db.models.User

Current user object

abstractmethod async get_token(grant_type: str | None = None, login: str | None = None, password: str | None = None, scopes: List[str] | None = None, client_id: str | None = None, client_secret: str | None = None) Dict[str, Any]

This method should perform authentication and return JWT token.

Parameters:
See:
Returns:
Dict:
{
    "access_token": "some.jwt.token",
    "token_type": "bearer",
    "expires_in": 3600,
}