DEV Community

Livio Ribeiro
Livio Ribeiro

Posted on

FastAPI with OIDC Discovery

FastAPI is a very nice tool for writing web applications in Python, it is very fast and is a joy to use. But saddly it still lacks support for openid-connect discovery, so I cannot simply point to my Keycloak instance and it configures itself.

Because of this I wrote FastAPI Resource Server, a helper that adds support to this scenario: setup issuer address, receive a JWT, validate and decode claims and return claims.

Usage is pretty straightforward, install with pip install fastapi-resource-server and configure your application:

from fastapi import Depends, FastAPI, Security
from pydantic import BaseModel

from fastapi_resource_server OidcResourceServer

app = FastAPI()

auth_scheme = OidcResourceServer(
    "https://issuer.url",
    scheme_name="My Issuer",
)


class User(BaseModel):
    sub: str
    username: str
    given_name: str
    family_name: str
    email: str


def get_current_user(claims: dict = Security(auth_scheme)):
    claims.update(username=claims["preferred_username"])
    user = User.parse_obj(claims)
    return user


@app.get("/users/me")
def read_current_user(current_user: User = Depends(get_current_user)):
    return current_user
Enter fullscreen mode Exit fullscreen mode

Under the hood it will fetch the openid configuration from {issuer_url}/.well-known/openid-configuration, then fetch the jwks from the jwks_uri property and use python-jose to decode the JWT.

And it works with the swagger ui with no problems.

Top comments (0)