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,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
|
||||
Reference in new issue
Block a user