71 lines
2.6 KiB
Python
71 lines
2.6 KiB
Python
"""
|
|
backend/app/services/auth/casdoor/identity.py
|
|
|
|
用途:将 Casdoor ID token/userinfo claims 转换为统一 AuthIdentity。
|
|
依赖:hmac、typing、services.auth.common.identity。
|
|
逻辑:严格绑定预期 issuer,提取稳定 subject 与可变用户资料,不访问业务数据库。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hmac
|
|
from collections.abc import Mapping
|
|
from typing import Any
|
|
|
|
from app.services.auth.common import AuthIdentity, IdentityValidationError, require_stable_identity
|
|
|
|
|
|
def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
|
|
"""按优先级读取第一个非空 claim 并转换为去空白字符串。"""
|
|
for key in keys:
|
|
value = claims.get(key)
|
|
if value is not None and str(value).strip():
|
|
return str(value).strip()
|
|
return None
|
|
|
|
|
|
def _claim_or_property_text(claims: Mapping[str, Any], *keys: str) -> str | None:
|
|
"""优先读取顶层 claim,再兼容 Casdoor properties 中同名的用户自定义属性。"""
|
|
value = _claim_text(claims, *keys)
|
|
if value:
|
|
return value
|
|
properties = claims.get('properties')
|
|
if isinstance(properties, Mapping):
|
|
return _claim_text(properties, *keys)
|
|
return None
|
|
|
|
|
|
def identity_from_claims(
|
|
claims: Mapping[str, Any],
|
|
*,
|
|
expected_issuer: str,
|
|
) -> AuthIdentity:
|
|
"""
|
|
将可信 Casdoor claims 转换为跨服务统一身份。
|
|
|
|
Args:
|
|
claims: 已验证 ID token 或通过 HTTPS 从 userinfo 获取的声明。
|
|
expected_issuer: 当前服务配置的可信 Casdoor issuer。
|
|
|
|
Returns:
|
|
不包含角色和业务权限的 AuthIdentity。
|
|
|
|
Raises:
|
|
IdentityValidationError: issuer 不匹配或缺少稳定 subject/username。
|
|
"""
|
|
trusted_issuer = str(expected_issuer or '').strip().rstrip('/')
|
|
claim_issuer = str(claims.get('iss') or trusted_issuer).strip().rstrip('/')
|
|
if not trusted_issuer or not claim_issuer or not hmac.compare_digest(claim_issuer, trusted_issuer):
|
|
raise IdentityValidationError('Casdoor identity issuer does not match the trusted issuer')
|
|
identity = AuthIdentity(
|
|
issuer=trusted_issuer,
|
|
subject=_claim_text(claims, 'sub') or '',
|
|
username=_claim_text(claims, 'preferred_username', 'name') or '',
|
|
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
|
|
email=_claim_text(claims, 'email'),
|
|
phone_number=_claim_text(claims, 'phone_number', 'phone'),
|
|
employee_id=_claim_or_property_text(claims, 'employee_id', 'employeeId'),
|
|
department=_claim_text(claims, 'department', 'affiliation'),
|
|
)
|
|
return require_stable_identity(identity)
|