r/FastAPI • • Apr 08 '22

Question Generic OIDC providers with FastAPI

Hi guys, is there a package in FastAPI that supports all generic OpenID connect providers? i've been trying to use AuthenticationX but the tutorial isn't explanatory enough. can i get recommendations?

3 Upvotes

2 comments sorted by

2

u/ejsyx Apr 10 '22

The fastapi docs don't provide examples for using OpenID connect, it does support the openapi security scheme out of the box.

Here's an example assuming your provider url is "http://localhost:8080/realms/tools/.well-known/openid-configuration" and your application id is "docs".

from fastapi.security import OpenIdConnect

oidc = OpenIdConnect(openIdConnectUrl="http://localhost:8080/realms/tools/.well-known/openid-configuration")
app = FastAPI(swagger_ui_init_oauth = {"clientId": "docs", 
"appName": "Doc Tools", 
"usePkceWithAuthorizationCodeGrant": True, 
"scopes": "openid profile",})

@app.get("/foo")
async def bar(token = Depends(oidc)):
    return token

Now this just adds openapi specification and syntactic sugar to access you jwt token, it doesn't do any security validation. For that you may look at any oauth2 middlewares or packages that fit your requirements. Example https://pypi.org/project/starlette-oauth2-api/

I don't know of well supported generic package that does all in one, however there are many articles/packages detailing the process for one specific provider you could support each provider with a different implementation. Also see fastapi issue discussion: https://github.com/tiangolo/fastapi/issues/840

1

u/Illustrious_Creme_58 Apr 10 '22

Thank you. I really appreciate I'll definitely look into it