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

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
小众软件
小众软件
美团技术团队
Martin Fowler
Martin Fowler
爱范儿
爱范儿
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
J
Java Code Geeks
B
Blog
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
博客园 - Franky

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