DEV Community

Livio Ribeiro
Livio Ribeiro

Posted on

5 3

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free