feat(auth): 重构统一认证并支持平级服务无感登录
This commit is contained in:
1 parent
d79def5519
commit
ca312ea751
64 files changed
+3713
-449
No files matched your search
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor/__init__.py
|
||||
|
||||
用途:导出不依赖 HXOPS User 模型的 Casdoor 认证公共能力。
|
||||
依赖:config、client、identity、errors。
|
||||
逻辑:HXOPS 与平级服务可复制本目录,并用各自配置适配器创建 CasdoorClient。
|
||||
"""
|
||||
|
||||
from .client import CasdoorClient, CasdoorTokenResult, get_casdoor_client
|
||||
from .config import CasdoorConfig, casdoor_config_from_flask
|
||||
from .identity import identity_from_claims
|
||||
|
||||
__all__ = [
|
||||
'CasdoorClient',
|
||||
'CasdoorConfig',
|
||||
'CasdoorTokenResult',
|
||||
'casdoor_config_from_flask',
|
||||
'get_casdoor_client',
|
||||
'identity_from_claims',
|
||||
]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor/client.py
|
||||
|
||||
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
|
||||
依赖:requests、CasdoorConfig、Casdoor 错误映射。
|
||||
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
from .config import CasdoorConfig, casdoor_config_from_flask
|
||||
from .errors import raise_auth_error
|
||||
|
||||
|
||||
_CLIENT_CACHE_LOCK = Lock()
|
||||
_CLIENT_CACHE_CONFIG: CasdoorConfig | None = None
|
||||
_CLIENT_CACHE_VALUE: CasdoorClient | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CasdoorTokenResult:
|
||||
"""Casdoor token endpoint 返回的标准字段和原始扩展字段。"""
|
||||
|
||||
access_token: str
|
||||
refresh_token: str | None
|
||||
id_token: str | None
|
||||
token_type: str
|
||||
expires_in: int
|
||||
raw: dict[str, Any]
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
"""返回兼容现有 HXOPS 路由和测试的 token 字典。"""
|
||||
return dict(self.raw)
|
||||
|
||||
|
||||
class CasdoorClient:
|
||||
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
|
||||
|
||||
def __init__(self, config: CasdoorConfig, *, http_session=requests):
|
||||
"""
|
||||
创建客户端并注入配置和 HTTP 实现。
|
||||
|
||||
Args:
|
||||
config: 当前服务自己的 Casdoor Application 配置。
|
||||
http_session: 兼容 requests 的 HTTP 对象,测试可注入替身。
|
||||
"""
|
||||
self.config = config
|
||||
self._http = http_session
|
||||
self._metadata: dict[str, Any] | None = None
|
||||
self._metadata_expires_at: datetime | None = None
|
||||
self._metadata_lock = Lock()
|
||||
|
||||
def oidc_metadata(self) -> dict[str, Any]:
|
||||
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
|
||||
return dict(self._metadata)
|
||||
with self._metadata_lock:
|
||||
now = datetime.now(timezone.utc)
|
||||
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
|
||||
return dict(self._metadata)
|
||||
response = self._http.get(
|
||||
f'{self.config.base_url}/.well-known/openid-configuration',
|
||||
timeout=self.config.timeout_seconds,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json() or {}
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError('Casdoor OIDC metadata is invalid')
|
||||
self._metadata = data
|
||||
self._metadata_expires_at = now + timedelta(minutes=10)
|
||||
return dict(data)
|
||||
|
||||
def _token_endpoint(self) -> str:
|
||||
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
|
||||
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise RuntimeError('Casdoor token endpoint missing')
|
||||
return endpoint
|
||||
|
||||
def _token_request(self, payload: dict[str, Any], *, context: str) -> CasdoorTokenResult:
|
||||
"""执行 token endpoint 请求并统一解析成功或失败结果。"""
|
||||
response = self._http.post(
|
||||
self._token_endpoint(),
|
||||
data=payload,
|
||||
timeout=self.config.timeout_seconds,
|
||||
)
|
||||
try:
|
||||
data = response.json() or {}
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f'Casdoor token request failed: HTTP {response.status_code}') from exc
|
||||
if not response.ok or not data.get('access_token'):
|
||||
raise_auth_error(data, context=context)
|
||||
return CasdoorTokenResult(
|
||||
access_token=str(data['access_token']),
|
||||
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
|
||||
id_token=str(data['id_token']) if data.get('id_token') else None,
|
||||
token_type=str(data.get('token_type') or 'Bearer'),
|
||||
expires_in=int(data.get('expires_in') or 3600),
|
||||
raw=dict(data),
|
||||
)
|
||||
|
||||
def password_login(self, username: str, password: str) -> CasdoorTokenResult:
|
||||
"""使用当前服务自己的 Casdoor Application 执行 password grant。"""
|
||||
return self._token_request({
|
||||
'grant_type': 'password',
|
||||
'username': username,
|
||||
'password': password,
|
||||
'client_id': self.config.client_id,
|
||||
'client_secret': self.config.client_secret,
|
||||
'scope': self.config.scope,
|
||||
}, context='password')
|
||||
|
||||
def authorization_code_login(self, code: str, redirect_uri: str) -> CasdoorTokenResult:
|
||||
"""将浏览器返回的 authorization code 兑换为 Casdoor token。"""
|
||||
return self._token_request({
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
'client_id': self.config.client_id,
|
||||
'client_secret': self.config.client_secret,
|
||||
'redirect_uri': redirect_uri,
|
||||
}, context='code')
|
||||
|
||||
def refresh(self, refresh_token: str) -> CasdoorTokenResult:
|
||||
"""使用 Casdoor refresh token 获取新 token 集合。"""
|
||||
return self._token_request({
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': refresh_token,
|
||||
'client_id': self.config.client_id,
|
||||
'client_secret': self.config.client_secret,
|
||||
}, context='refresh')
|
||||
|
||||
def userinfo(self, access_token: str) -> dict[str, Any]:
|
||||
"""使用 Casdoor access token 获取可信用户声明。"""
|
||||
endpoint = str(self.oidc_metadata().get('userinfo_endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise RuntimeError('Casdoor userinfo endpoint missing')
|
||||
response = self._http.get(
|
||||
endpoint,
|
||||
headers={'Authorization': f'Bearer {access_token}'},
|
||||
timeout=self.config.timeout_seconds,
|
||||
)
|
||||
try:
|
||||
data = response.json() or {}
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}') from exc
|
||||
if not response.ok or not isinstance(data, dict):
|
||||
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}')
|
||||
return data
|
||||
|
||||
|
||||
def get_casdoor_client() -> CasdoorClient:
|
||||
"""复用当前配置对应的进程内客户端,配置变化时自动替换缓存实例。"""
|
||||
global _CLIENT_CACHE_CONFIG, _CLIENT_CACHE_VALUE
|
||||
|
||||
config = casdoor_config_from_flask()
|
||||
if _CLIENT_CACHE_VALUE is not None and _CLIENT_CACHE_CONFIG == config:
|
||||
return _CLIENT_CACHE_VALUE
|
||||
with _CLIENT_CACHE_LOCK:
|
||||
if _CLIENT_CACHE_VALUE is None or _CLIENT_CACHE_CONFIG != config:
|
||||
_CLIENT_CACHE_CONFIG = config
|
||||
_CLIENT_CACHE_VALUE = CasdoorClient(config)
|
||||
return _CLIENT_CACHE_VALUE
|
||||
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor/config.py
|
||||
|
||||
用途:定义纯 Casdoor 客户端配置及 HXOPS Flask 配置适配器。
|
||||
依赖:dataclasses、flask.current_app、app.core.errors。
|
||||
逻辑:公共客户端只接收 CasdoorConfig;不同服务只需替换配置适配器。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CasdoorConfig:
|
||||
"""Casdoor OAuth/OIDC 客户端运行参数,secret 不参与 repr。"""
|
||||
|
||||
base_url: str
|
||||
client_id: str
|
||||
client_secret: str
|
||||
issuer: str
|
||||
scope: str = 'openid profile email'
|
||||
timeout_seconds: int = 8
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""输出可诊断但不包含 client_secret 的配置摘要。"""
|
||||
return (
|
||||
'CasdoorConfig('
|
||||
f'base_url={self.base_url!r}, client_id={self.client_id!r}, '
|
||||
f'issuer={self.issuer!r}, scope={self.scope!r}, '
|
||||
f'timeout_seconds={self.timeout_seconds!r})'
|
||||
)
|
||||
|
||||
|
||||
def casdoor_config_from_flask() -> CasdoorConfig:
|
||||
"""
|
||||
从当前 Flask 应用读取并校验 Casdoor 客户端配置。
|
||||
|
||||
Returns:
|
||||
可交给 CasdoorClient 的不可变配置。
|
||||
|
||||
Raises:
|
||||
AppError: 基础地址、客户端凭据或 issuer 未配置。
|
||||
"""
|
||||
base_url = str(current_app.config.get('CASDOOR_BASE_URL') or '').strip().rstrip('/')
|
||||
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '').strip()
|
||||
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
|
||||
issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip().rstrip('/')
|
||||
scope = str(current_app.config.get('CASDOOR_SCOPE') or 'openid profile email').strip()
|
||||
timeout_seconds = int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8)
|
||||
if not base_url or not client_id or not client_secret or not issuer:
|
||||
raise AppError(
|
||||
code='CASDOOR_CONFIG_ERROR',
|
||||
message='Authentication service is not configured. Please contact the administrator.',
|
||||
http_status=503,
|
||||
)
|
||||
return CasdoorConfig(
|
||||
base_url=base_url,
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
issuer=issuer,
|
||||
scope=scope or 'openid profile email',
|
||||
timeout_seconds=max(1, timeout_seconds),
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor/errors.py
|
||||
|
||||
用途:把 Casdoor OAuth/OIDC 失败转换为稳定业务错误码。
|
||||
依赖:标准库解析工具、flask.current_app、app.core.errors。
|
||||
逻辑:CasdoorClient 将失败响应交给本模块,API 层只处理统一 AppError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import AppError, ValidationError
|
||||
|
||||
|
||||
def clean_str(value) -> str | None:
|
||||
"""去除字符串首尾空白,空值统一返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
return str(value).strip() or None
|
||||
|
||||
|
||||
def extract_error_payload(source) -> dict:
|
||||
"""从 Casdoor 响应字典或异常文本中提取可识别错误字段。"""
|
||||
if isinstance(source, dict):
|
||||
return source
|
||||
text = str(source or '')
|
||||
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = ast.literal_eval(match.group(0))
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (SyntaxError, ValueError):
|
||||
pass
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return {}
|
||||
|
||||
|
||||
def is_password_error(message: str) -> bool:
|
||||
"""判断 Casdoor 错误是否表示用户名或密码无效。"""
|
||||
lowered = (message or '').lower()
|
||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||
|
||||
|
||||
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
"""
|
||||
将 Casdoor 登录、授权码和刷新失败映射为稳定错误。
|
||||
|
||||
Args:
|
||||
source: Casdoor JSON 错误体或捕获的异常。
|
||||
context: ``password``、``code``、``refresh`` 或 ``verify``。
|
||||
status_code: 未识别错误的默认 HTTP 状态码。
|
||||
|
||||
Raises:
|
||||
AppError: 所有失败均转换为统一认证错误,不返回原始 token 或 secret。
|
||||
"""
|
||||
data = extract_error_payload(source)
|
||||
raw = str(source or '')
|
||||
oauth_error = (clean_str(data.get('error')) or '').lower()
|
||||
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||
oauth_error = 'invalid_grant'
|
||||
if not oauth_error and 'invalid_client' in raw.lower():
|
||||
oauth_error = 'invalid_client'
|
||||
if oauth_error == 'invalid_grant' or is_password_error(raw):
|
||||
if context in {'password', 'verify'}:
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||
if oauth_error in {'invalid_client', 'unauthorized_client'}:
|
||||
raise AppError(
|
||||
code='CASDOOR_CONFIG_ERROR',
|
||||
message='Authentication service is misconfigured. Please contact the administrator.',
|
||||
http_status=503,
|
||||
details={'casdoor_error': oauth_error},
|
||||
)
|
||||
if oauth_error == 'access_denied':
|
||||
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||
if oauth_error == 'unsupported_grant_type':
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
lowered_raw = raw.lower()
|
||||
if 'token endpoint missing' in lowered_raw or 'casdoor_base_url is not configured' in lowered_raw:
|
||||
raise AppError(
|
||||
code='CASDOOR_CONFIG_ERROR',
|
||||
message='Authentication service is not configured. Please contact the administrator.',
|
||||
http_status=503,
|
||||
)
|
||||
if 'invalid or expired casdoor state' in lowered_raw:
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
|
||||
raise AppError(
|
||||
code='CASDOOR_AUTH_FAILED',
|
||||
message='Authentication failed, please try again',
|
||||
http_status=status_code,
|
||||
details={'casdoor_error': oauth_error or None},
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
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 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_text(claims, 'employee_id', 'employeeId'),
|
||||
department=_claim_text(claims, 'department', 'affiliation'),
|
||||
)
|
||||
return require_stable_identity(identity)
|
||||
Reference in new issue
Block a user