feat: add username-password login flow via authentik token endpoint

This commit is contained in:
Chris
2026-03-30 00:52:09 +08:00
parent 8335dc11d1
commit 8f06f75cca
8 changed files with 83 additions and 0 deletions

57
app/api/auth.py Normal file
View File

@@ -0,0 +1,57 @@
from urllib.parse import urljoin
import httpx
from fastapi import APIRouter, HTTPException, status
from app.core.config import get_settings
from app.schemas.login import LoginRequest, LoginResponse
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login", response_model=LoginResponse)
def login(payload: LoginRequest) -> LoginResponse:
settings = get_settings()
client_id = settings.authentik_client_id or settings.authentik_audience
if not settings.authentik_base_url or not client_id or not settings.authentik_client_secret:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
token_endpoint = settings.authentik_token_endpoint or urljoin(
settings.authentik_base_url.rstrip("/") + "/", "application/o/token/"
)
form = {
"grant_type": "password",
"client_id": client_id,
"client_secret": settings.authentik_client_secret,
"username": payload.username,
"password": payload.password,
"scope": "openid profile email",
}
try:
resp = httpx.post(
token_endpoint,
data=form,
timeout=10,
verify=settings.authentik_verify_tls,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
except Exception as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
if resp.status_code >= 400:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid_username_or_password")
data = resp.json()
token = data.get("access_token")
if not token:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_missing_access_token")
return LoginResponse(
access_token=token,
token_type=data.get("token_type", "Bearer"),
expires_in=data.get("expires_in"),
scope=data.get("scope"),
)

View File

@@ -23,7 +23,9 @@ class Settings(BaseSettings):
authentik_issuer: str = ""
authentik_jwks_url: str = ""
authentik_audience: str = ""
authentik_client_id: str = ""
authentik_client_secret: str = ""
authentik_token_endpoint: str = ""
public_frontend_origins: Annotated[list[str], NoDecode] = ["https://member.ose.tw"]
internal_shared_secret: str = ""

View File

@@ -2,6 +2,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.admin import router as admin_router
from app.api.auth import router as auth_router
from app.api.internal import router as internal_router
from app.api.me import router as me_router
from app.core.config import get_settings
@@ -26,3 +27,4 @@ def healthz() -> dict[str, str]:
app.include_router(internal_router)
app.include_router(admin_router)
app.include_router(me_router)
app.include_router(auth_router)

13
app/schemas/login.py Normal file
View File

@@ -0,0 +1,13 @@
from pydantic import BaseModel
class LoginRequest(BaseModel):
username: str
password: str
class LoginResponse(BaseModel):
access_token: str
token_type: str = "Bearer"
expires_in: int | None = None
scope: str | None = None