212 lines
8.5 KiB
Python
212 lines
8.5 KiB
Python
"""
|
|
backend/app/services/auth/casdoor/client.py
|
|
|
|
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
|
|
依赖:requests、CasdoorConfig、Casdoor 错误映射。
|
|
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
|
|
discovery 仍可能广告 HTTPS 域名,服务端换票和 userinfo 会改写到 CASDOOR_BASE_URL。
|
|
"""
|
|
|
|
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)
|
|
|
|
|
|
# 仅改写后端自己调用的端点。authorization_endpoint 留给浏览器,避免把用户重定向到内网地址。
|
|
_SERVER_ENDPOINT_KEYS = (
|
|
'token_endpoint',
|
|
'userinfo_endpoint',
|
|
'jwks_uri',
|
|
'introspection_endpoint',
|
|
)
|
|
|
|
|
|
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 分钟。
|
|
|
|
核心逻辑:先请求 CASDOOR_BASE_URL 上的 discovery。若换票、userinfo、JWKS
|
|
仍指向 AUTH_JWT_ISSUER 的 HTTPS 源,改写到 CASDOOR_BASE_URL,避开过期证书。
|
|
浏览器使用的 authorization_endpoint 保持 discovery 原值。
|
|
"""
|
|
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')
|
|
# [STEP 1] 公网证书过期时,Casdoor 仍在 discovery 里广告 HTTPS 域名。
|
|
# 后端改走已配置的 HTTP 入口,令牌 iss 仍按 AUTH_JWT_ISSUER 校验。
|
|
data = self._rewrite_server_endpoints(data)
|
|
self._metadata = data
|
|
self._metadata_expires_at = now + timedelta(minutes=10)
|
|
return dict(data)
|
|
|
|
def _rewrite_server_endpoints(self, data: dict[str, Any]) -> dict[str, Any]:
|
|
"""
|
|
把 discovery 中指向签发方源站的服务端地址改写到 CASDOOR_BASE_URL。
|
|
|
|
Args:
|
|
data: Casdoor openid-configuration JSON。
|
|
|
|
Returns:
|
|
改写 token、userinfo、jwks 后的文档。签发方与 base URL 相同时原样返回。
|
|
"""
|
|
issuer = self.config.issuer.rstrip('/')
|
|
base_url = self.config.base_url.rstrip('/')
|
|
if not issuer or not base_url or issuer == base_url:
|
|
return data
|
|
prefix = f'{issuer}/'
|
|
rewritten = dict(data)
|
|
for key in _SERVER_ENDPOINT_KEYS:
|
|
value = str(rewritten.get(key) or '').strip()
|
|
if value == issuer or value.startswith(prefix):
|
|
rewritten[key] = f'{base_url}{value[len(issuer):]}'
|
|
return rewritten
|
|
|
|
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
|