Package: fastapi-oauth-client
Authorization and Authentication for FastAPI ApplicationsThis repository provides a package that facilitates token-based authentication and authorization within yourFastAPIapplication.It builds on top ofAuthliband provides a simple interface for protecting your own FastAPI endpoints with token-based authentication using OAuth.It is the result of a client project ofSchroeck IT Consulting.
The goal was a simple FastAPI integration with Keycloak without much manual interference needed. Hence, the code is very much focused on Keycloak.However, it should work for most other OAuth IdP's. If you require RBAC (Role-based access), make sure to name the claim containing the roles,roles.FeaturesGet an API token for your fastAPI app using your favorite IdP via OAuth. This library simplifies the process by giving you the required endpoints and the login mechanismProtect your endpoints by just adding a dependency to the endpoint functionsSupport for role-based access control for endpointsContactThis library was originally published bySchroeck IT-Consulting.Email:hello@schroeck-consulting.deInstallationSimply pull the package from Pypi:bash pip install fastapi_oauth_clientOverviewThis package enhances your FastAPI application by incorporating token-based authentication and authorization mechanisms.Key Features:Addition of two endpoints,/loginand/callback, implementing the standard OAuth / OpenID connect flow via a web browser.Users authenticate through the/loginendpoint, which redirects them to the Identity Provider (IdP), such as Keycloak, for login.Upon successful login, users are returned to the FastAPI app with an access token obtained from the IdP.With the obtained access token, your FastAPI app gains the ability to access protected endpoints. This token remains valid for machine-to-machine communication until its expiration.Implementation StepsTo integrate this package into your FastAPI app, follow these steps:Configure OAuth settings by setting the necessary environment variables. Refer to theexample.envfile. For testing purposes, update settings in that, and run FastAPI using the command:sh ./run.sh.Incorporate the login endpoints into your code:fromfastapi_oauth_clientimportauth_router,verify_tokenfromstarlette.middleware.sessionsimportSessionMiddlewarefromfastapiimportFastAPIimportsecretsapp=FastAPI(title="Your App Name",version="1.0.0",description="Description of your app.",openapi_tags={},)# Integrate the login endpointsapp.add_middleware(SessionMiddleware,secret_key=secrets.token_urlsafe(16))app.include_router(auth_router)Secure your endpoints using the access token:fromfastapi_oauth_clientimportauth_router,verify_tokenfromfastapiimportDepends,FastAPIimportsecretsfromstarlette.middleware.sessionsimportSessionMiddlewareapp=FastAPI(title="Your App Name",version="1.0.0",description="Description of your app.",openapi_tags={},)# Integrate the login endpointsapp.add_middleware(SessionMiddleware,secret_key=secrets.token_urlsafe(16))app.include_router(auth_router)@app.get("/protected_endpoint")defdoSomething(profile=Depends(verify_token(roles=["admin"]))):"""Docstring..."""return"OK"Note: It's crucial to declare the 'SessionMiddleware'. This declaration enables FastAPI app to extract the Bearer token from the incoming request.Keycloak ConfigurationBefore proceeding, ensure you've configured a client in Keycloak. Assuming this is done, follow these steps to extend token lifetime:Realm Settings: Navigate to the realm settings in the Keycloak administration console. Access the "Sessions" tab and extend the session lifetime as shown:Adjust Client Settings: Next, extend the token lifetime for the specific client. Select the client and head to the "Advanced" settings tab:Accessing Protected EndpointsTo access protected endpoints, include theAuthorizationheader in your
requests. Provide the Bearer token obtained after login:GET/protected_endpointHTTP/1.1Host: your-api-host

Authorization: Bearer ey...Log LevelThis package uses Loguru for logging. To adjust its loglevel, use the environment variableLOG_LEVEL.