惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
MyScale Blog
MyScale Blog
A
About on SuperTechFans
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
The Cloudflare Blog
F
Fortinet All Blogs
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
罗磊的独立博客
量子位
有赞技术团队
有赞技术团队
V
V2EX
Engineering at Meta
Engineering at Meta

Gary' Blog

Migrate pip to uv - Gary' Blog Terminal autocomplete (only macOS and Linux) How to expand the hard disk capacity of Debian/Ubuntu in ESXi Keycloak configuration problems and solutions Careers and LinkedIn Jobs Page of Fortune 500 American Companies How to connect Windows desktop remotely using RDP and cloudflare ZeroTrust tunnel ESXi 8 issue solved: This PC can’t run Windows 11 How to download and license ESXi 8? Get clicked word using pure Javascript
Authentication FastAPI with Keycloak - Gary' Blog
Gary · 2025-02-04 · via Gary' Blog

First you need to create a realm and client, and get the client id and secret.

Go to Keycloak configuration problems and solutions to see how to setup at Keycloak Admin Panel.

1 Install dependencies

pip install python-jose[cryptography]>=3.3.0
pip install cryptography>=3.4.0
pip install PyJWT==2.10.1

Setup configuration

Add following to your configuration file, like config.py:

from os import getenv

# Keycloak Settings
KEYCLOAK_URL = getenv("KEYCLOAK_URL")
KEYCLOAK_REALM = getenv("KEYCLOAK_REALM")
KEYCLOAK_CLIENT_ID = getenv("KEYCLOAK_CLIENT_ID")
KEYCLOAK_CLIENT_SECRET = getenv("KEYCLOAK_CLIENT_SECRET") 
KEYCLOAK_ALGORITHM = getenv("KEYCLOAK_ALGORITHM", "ES256")

# OpenID Connect endpoints
OIDC_JWKS_URI = f"{KEYCLOAK_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/certs"
OIDC_TOKEN_ENDPOINT = f"{KEYCLOAK_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/token"

2 Add Authentication Service

let’s name it auth_service.py:

from typing import Dict, Any
from jose import jwt, JWTError
from jose.exceptions import JWTClaimsError
from jwt import PyJWKClient
from fastapi import HTTPException, Depends, status
from fastapi.security import OAuth2PasswordBearer

from src.config import (
    KEYCLOAK_ALGORITHM,
    OIDC_JWKS_URI,
    OIDC_TOKEN_ENDPOINT,
    KEYCLOAK_CLIENT_ID,
    KEYCLOAK_CLIENT_SECRET,
)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=OIDC_TOKEN_ENDPOINT)
jwks_client = PyJWKClient(OIDC_JWKS_URI)

def decode_token(token: str) -> Dict[str, Any]:
    try:
        # Extract the key from the JWKS endpoint
        signing_key = jwks_client.get_signing_key_from_jwt(token).key

        # Decode and verify the token
        payload = jwt.decode(
            token,
            signing_key,
            algorithms=[KEYCLOAK_ALGORITHM],
            audience=KEYCLOAK_CLIENT_ID,
            options={"verify_exp": True}
        )
        return payload
    except JWTClaimsError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid token claims: {str(e)}"
        )
    except JWTError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid token: {str(e)}",
            headers={"WWW-Authenticate": "Bearer"},
        )

async def get_current_user(token: str = Depends(oauth2_scheme)):
    if not KEYCLOAK_CLIENT_SECRET:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Keycloak client secret not configured"
        )

    payload = decode_token(token)
    if not payload:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return payload