feat(auth): 重构统一认证并支持平级服务无感登录

This commit is contained in:
sophie committed 2026-07-28 09:15:41 +08:00
1 parent d79def5519
commit ca312ea751
64 files changed
+3713 -449

No files matched your search

+4 -3
View File
@@ -13,11 +13,12 @@ LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
AUTH_LOGIN_MODE=password
# AUTH_LOGIN_MODE=password
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
AUTH_LOGIN_MODE=casdoor
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
AUTH_JWT_ISSUER=https://autht.well-trust.com
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
+2 -1
View File
@@ -17,7 +17,8 @@ AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
AUTH_JWT_ISSUER=https://autht.well-trust.com
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
+2
View File
@@ -69,6 +69,8 @@ Thumbs.db
# tmp
.tmp/
.tmp2/
.sso-pytest-temp/
.pytest-sso-run*/
.npm-cache
.npm-cache2
+1 -1
View File
@@ -118,7 +118,7 @@ def create_app(config_name='default'):
return wrapped_resp
def _should_return_json_error() -> bool:
if request.path.startswith('/api/'):
if request.path.startswith('/api/') or request.path == '/.well-known/jwks.json':
return True
accepted = request.headers.get('Accept', '')
return 'application/json' in accepted.lower()
+3
View File
@@ -26,6 +26,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.internal_jobs import internal_jobs_bp
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.sso import sso_bp, sso_well_known_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
@@ -61,6 +62,8 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(sso_bp, url_prefix='/api/sso')
app.register_blueprint(sso_well_known_bp)
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
+66
View File
@@ -0,0 +1,66 @@
"""
backend/app/api/sso.py
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
Flow: Authenticated browsers request audience-bound assertions; peer-service backends verify them using JWKS.
"""
from __future__ import annotations
from flask import Blueprint, g, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, UnauthorizedError, ValidationError
from app.services.auth.sso import build_jwks, issue_assertion, list_applications
sso_bp = Blueprint('sso', __name__)
sso_well_known_bp = Blueprint('sso_well_known', __name__)
def _require_active_user():
"""Resolve an active Bearer-authenticated user and retain verified JWT claims."""
authorization = str(request.headers.get('Authorization') or '').strip()
scheme, _, token = authorization.partition(' ')
if scheme.lower() != 'bearer' or not token.strip():
raise UnauthorizedError('Bearer token is required')
user = get_current_user()
if user is None:
raise UnauthorizedError('Unauthorized')
claims = dict(getattr(g, 'jwt_claims', None) or {})
if not claims:
raise UnauthorizedError('Verified Bearer token is required')
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
return user, claims
@sso_bp.route('/apps', methods=['GET'])
def list_sso_apps():
"""Return enabled application navigation metadata to authenticated HXOPS users."""
_require_active_user()
return jsonify({'items': [application.public_payload() for application in list_applications()]})
@sso_bp.route('/apps/<string:app_key>/assertions', methods=['POST'])
def create_sso_assertion(app_key: str):
"""Issue a short-lived RS256 assertion and return the registered peer callback URL."""
user, claims = _require_active_user()
data = request.get_json(silent=True) or {}
if not isinstance(data, dict):
raise ValidationError('JSON body is required')
return jsonify(issue_assertion(
app_key=app_key,
user=user,
claims=claims,
state=data.get('state'),
))
@sso_well_known_bp.route('/.well-known/jwks.json', methods=['GET'])
def sso_jwks():
"""Publish active and rotation-window product SSO public keys for offline peer verification."""
response = jsonify(build_jwks())
response.headers['Cache-Control'] = 'public, max-age=300'
return response
+89 -112
View File
@@ -14,7 +14,6 @@ from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
from app.core.auth.jwt import issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
@@ -38,6 +37,8 @@ from app.core.errors import (
raise_for_status,
)
from app.services.auth import casdoor_service as _casdoor_svc
from app.services.auth.casdoor import get_casdoor_client
from app.services.auth.hxops.login_service import HxopsLoginService
from app.services.auth import wecom_auth_service as _wecom_svc
user_bp = Blueprint('user', __name__)
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
@@ -47,7 +48,6 @@ _PASSWORD_RESET_RATE_CACHE = {}
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
_LOGIN_AUDIT_COLUMNS_CACHE = None
_CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None}
def _token_brief(token: str) -> str:
if not token:
@@ -174,84 +174,91 @@ def _consume_casdoor_state(state: str):
return _clean_str(payload.get('redirect_uri'))
def _get_casdoor_oidc_metadata():
now = datetime.utcnow()
cached = _CASDOOR_OIDC_CACHE.get('value')
exp = _CASDOOR_OIDC_CACHE.get('expires_at')
if cached and exp and (exp > now):
return cached
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
if not base:
raise RuntimeError('CASDOOR_BASE_URL is not configured')
resp = requests.get(f'{base}/.well-known/openid-configuration', timeout=8)
resp.raise_for_status()
data = resp.json() or {}
_CASDOOR_OIDC_CACHE['value'] = data
_CASDOOR_OIDC_CACHE['expires_at'] = now + timedelta(minutes=10)
return data
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
return get_casdoor_client().oidc_metadata()
def _resolve_user_from_casdoor_claims(claims: dict):
username = _clean_str(claims.get('preferred_username')) or _clean_str(claims.get('name'))
email = _clean_str(claims.get('email'))
current_app.logger.info('[casdoor_login] claims preferred_username=%s name=%s email=%s sub=%s', _clean_str(claims.get('preferred_username')), _clean_str(claims.get('name')), email, _clean_str(claims.get('sub')))
user = None
if username:
user = db.session.query(User).filter_by(username=username).first()
if not user and email:
user = db.session.query(User).filter_by(email=email).first()
if not user:
raise WeComLoginError(error='No local user matched Casdoor identity. Please contact admin to provision account.', error_code='CASDOOR_USER_NOT_FOUND', status_code=403)
if user.status != 'active':
raise WeComLoginError(error='Account is disabled', error_code='ACCOUNT_DISABLED', status_code=403)
return user
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
return resolve_hxops_user(identity)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
except HxopsIdentityMappingError as exc:
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
"""
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
Args:
user: 已映射成功的 HXOPS 本地用户。
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
Returns:
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
Raises:
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.session_token import issue_hxops_access_token
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
return issue_hxops_access_token(user, identity)
def _casdoor_exchange_code(code: str, redirect_uri: str):
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
if not token_endpoint:
raise RuntimeError('Casdoor token endpoint missing')
payload = {'grant_type': 'authorization_code', 'code': code, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'redirect_uri': redirect_uri or (current_app.config.get('CASDOOR_REDIRECT_URI') or '')}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='code')
return data
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
def _casdoor_refresh_token(refresh_token: str):
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or ''}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='refresh')
return data
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
return get_casdoor_client().refresh(refresh_token).as_dict()
def _casdoor_userinfo(access_token: str):
meta = _get_casdoor_oidc_metadata()
userinfo_endpoint = meta.get('userinfo_endpoint')
if not userinfo_endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
resp = requests.get(userinfo_endpoint, headers={'Authorization': f'Bearer {access_token}'}, timeout=8)
data = resp.json() or {}
if not resp.ok:
raise RuntimeError(f'Casdoor userinfo failed: {data}')
return data
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
return get_casdoor_client().userinfo(access_token)
def _casdoor_password_login(username: str, password: str):
"""
Resource-owner password login against Casdoor token endpoint.
Requires the Casdoor application to enable password grant.
"""
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
if not token_endpoint:
raise RuntimeError('Casdoor token endpoint missing')
payload = {'grant_type': 'password', 'username': username, 'password': password, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'scope': current_app.config.get('CASDOOR_SCOPE') or 'openid profile email'}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='password')
return data
return get_casdoor_client().password_login(username, password).as_dict()
def _hxops_login_service() -> HxopsLoginService:
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
return HxopsLoginService(
password_login=_casdoor_password_login,
authorization_code_login=_casdoor_exchange_code,
refresh_token=_casdoor_refresh_token,
userinfo=_casdoor_userinfo,
write_login_audit=_write_login_audit,
)
def _is_casdoor_login_mode() -> bool:
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
@@ -753,24 +760,9 @@ def casdoor_password_login():
if not username or not password:
raise ValidationError('Username and password are required')
try:
token_data = _casdoor_password_login(username, password)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
id_token = token_data.get('id_token')
expires_in = int(token_data.get('expires_in') or 3600)
claims = None
if id_token:
try:
claims = _decode_jwt(id_token)
except Exception:
claims = None
if claims is None:
claims = _casdoor_userinfo(access_token)
user = _resolve_user_from_casdoor_claims(claims)
_write_login_audit('casdoor', 'success', user=user)
result = _hxops_login_service().password(username, password)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify(result.login_payload())
except WeComLoginError:
db.session.rollback()
raise
@@ -853,7 +845,7 @@ def casdoor_login():
"role": "<local role>",
"default_agent_id": <int|null>,
"source": "casdoor",
"access_token": "<casdoor access token>",
"access_token": "<HXOPS API session JWT>",
"refresh_token": "<casdoor refresh token>",
"id_token": "<casdoor id token|nullable>",
"token_type": "Bearer",
@@ -881,26 +873,10 @@ def casdoor_login():
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
raise ValidationError('Invalid or expired Casdoor state')
try:
token_data = _casdoor_exchange_code(code, redirect_uri)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
id_token = token_data.get('id_token')
expires_in = int(token_data.get('expires_in') or 3600)
current_app.logger.info('[casdoor_login] token_exchange_ok redirect_uri=%s access=%s refresh=%s id=%s', redirect_uri, _token_brief(access_token), _token_brief(refresh_token), _token_brief(id_token))
claims = None
if id_token:
try:
claims = _decode_jwt(id_token)
except Exception:
claims = None
if claims is None:
claims = _casdoor_userinfo(access_token)
user = _resolve_user_from_casdoor_claims(claims)
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', user.username, user.id)
_write_login_audit('casdoor', 'success', user=user)
result = _hxops_login_service().authorization_code(code, redirect_uri)
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify(result.login_payload())
except WeComLoginError:
db.session.rollback()
current_app.logger.warning('[casdoor_login] business_reject')
@@ -927,7 +903,7 @@ def casdoor_refresh():
Response 200:
{
"access_token": "<new access token>",
"access_token": "<new HXOPS API session JWT>",
"refresh_token": "<possibly rotated refresh token>",
"id_token": "<optional id token>",
"token_type": "Bearer",
@@ -946,14 +922,15 @@ def casdoor_refresh():
raise ValidationError('refresh_token is required')
current_app.logger.info('[casdoor_refresh] start refresh=%s', _token_brief(refresh_token))
try:
token_data = _casdoor_refresh_token(refresh_token)
access_token = token_data.get('access_token')
id_token = token_data.get('id_token')
next_refresh = token_data.get('refresh_token') or refresh_token
expires_in = int(token_data.get('expires_in') or 3600)
current_app.logger.info('[casdoor_refresh] token_refresh_ok access=%s id=%s next_refresh=%s', _token_brief(access_token), _token_brief(id_token), _token_brief(next_refresh))
api_bearer_token = id_token or access_token
return jsonify({'access_token': api_bearer_token, 'refresh_token': next_refresh, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
result = _hxops_login_service().refresh(refresh_token)
current_app.logger.info(
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
_token_brief(result.refresh_token),
result.user.id,
)
return jsonify(result.refresh_payload())
except AppError:
raise
except Exception as e:
message = str(e)
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
+23 -2
View File
@@ -294,8 +294,23 @@ def get_current_user() -> Optional[User]:
return None
def issue_local_access_token(user: User) -> str:
"""签发本地 HS256 JWT(密码登录兼容)。"""
def issue_local_access_token(
user: User,
*,
casdoor_issuer: str | None = None,
casdoor_subject: str | None = None,
) -> str:
"""
签发 HXOPS API 会话 JWT。
Args:
user: 已完成认证并映射到 HXOPS 的本地用户。
casdoor_issuer: Casdoor 身份签发者;仅 Casdoor 登录成功后写入。
casdoor_subject: Casdoor 稳定用户 subject;必须与 issuer 同时提供。
Returns:
由 HXOPS SECRET_KEY 签名、供本站 API 使用的 HS256 JWT。
"""
now = datetime.now(timezone.utc)
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
payload = {
@@ -310,5 +325,11 @@ def issue_local_access_token(user: User) -> str:
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
}
normalized_issuer = str(casdoor_issuer or '').strip()
normalized_subject = str(casdoor_subject or '').strip()
if normalized_issuer and normalized_subject:
# 标准 iss/sub 仍属于 HXOPS 会话;Casdoor 身份单独保存,避免混淆两个信任域。
payload['casdoor_iss'] = normalized_issuer
payload['casdoor_sub'] = normalized_subject
secret = current_app.config.get('SECRET_KEY')
return jwt.encode(payload, secret, algorithm='HS256')
+12 -1
View File
@@ -76,6 +76,7 @@ def _backend_path(env_key: str, *parts: str) -> str:
class Config:
ENV_NAME = ACTIVE_ENV_NAME
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
# 配置最大上传文件大小(200MB)
@@ -327,7 +328,7 @@ class Config:
# Login mode switch: "casdoor" (default) or "password".
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
# password: keep legacy local username/password login.
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
AUTH_LOGIN_MODE = (os.getenv('AUTH_LOGIN_MODE') or 'casdoor').strip().lower()
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
@@ -338,6 +339,7 @@ class Config:
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
CASDOOR_HTTP_TIMEOUT_SECONDS = int(os.getenv('CASDOOR_HTTP_TIMEOUT_SECONDS', '8') or '8')
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
@@ -347,6 +349,15 @@ class Config:
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
# Product SSO: HXOPS signs short-lived, audience-bound RS256 assertions for registered peer services.
SSO_ENABLED = os.getenv('SSO_ENABLED', 'false').lower() == 'true'
SSO_APPS_JSON = os.getenv('SSO_APPS_JSON', '[]')
SSO_ASSERTION_TTL_SECONDS = int(os.getenv('SSO_ASSERTION_TTL_SECONDS', '60') or '60')
SSO_ISSUER = os.getenv('SSO_ISSUER', '').strip()
SSO_SIGNING_ALGORITHM = os.getenv('SSO_SIGNING_ALGORITHM', 'RS256').strip().upper()
SSO_SIGNING_KEY_ID = os.getenv('SSO_SIGNING_KEY_ID', '').strip()
SSO_PRIVATE_KEY_PATH = os.getenv('SSO_PRIVATE_KEY_PATH', '').strip()
SSO_ADDITIONAL_PUBLIC_KEYS_JSON = os.getenv('SSO_ADDITIONAL_PUBLIC_KEYS_JSON', '[]')
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
@@ -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',
]
+170
View File
@@ -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),
)
+106
View File
@@ -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)
+53 -321
View File
@@ -1,373 +1,105 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
用途:为历史调用点保留 Casdoor 错误与 HXOPS 用户同步兼容门面。
依赖:公共 casdoor.errors、HXOPS casdoor_user_sync。
逻辑:新代码按职责导入分层模块;旧路由、管理端和测试可继续替换本文件函数。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
from app.services.auth.casdoor.errors import (
clean_str,
extract_error_payload,
is_password_error,
raise_auth_error,
)
from app.services.auth.hxops import casdoor_user_sync as _sync
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
"""兼容入口:检查 Casdoor 用户同步配置。"""
return _sync.is_casdoor_configured()
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
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)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
"""兼容入口:返回 Casdoor organization owner。"""
return _sync.casdoor_user_owner()
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
"""兼容入口:判断 IdP 用户已存在错误。"""
return _sync.is_user_exists_error(message)
def is_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
"""兼容入口:判断 IdP 用户不存在错误。"""
return _sync.is_user_missing_error(message)
def raise_user_not_in_idp(source=None) -> None:
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:抛出 IdP 缺失用户业务错误。"""
_sync.raise_user_not_in_idp(source)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 新增用户错误。"""
_sync.raise_add_user_error(source)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 更新用户错误。"""
_sync.raise_update_user_error(source)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
"""兼容入口:映射 Casdoor 修改密码错误。"""
_sync.raise_set_password_error(source)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).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 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
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 raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造不含密码的 Casdoor 用户资料。"""
return _sync.build_user_profile_payload(**kwargs)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
display_name = clean_str(real_name) or username
payload = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造 Casdoor 创建用户请求体。"""
return _sync.build_user_payload(**kwargs)
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 创建用户。"""
_sync.casdoor_add_user(user_payload)
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 更新用户。"""
_sync.casdoor_update_user(user_payload)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(
url,
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=8,
)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_set_password_error(data)
"""兼容入口:调用 Casdoor 修改密码。"""
_sync.casdoor_set_password(user_owner, user_name, old_password, new_password)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
casdoor_add_user(payload)
def sync_create_user(**kwargs) -> None:
"""兼容入口:同步创建用户,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_create_user(**kwargs, add_user=casdoor_add_user)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
if not is_casdoor_configured():
return
user_owner = casdoor_user_owner()
try:
casdoor_set_password(user_owner, user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
"""兼容入口:同步管理员改密,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_admin_set_password(user, new_password, set_password=casdoor_set_password)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
sync_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
"""兼容入口:同步用户改密或补建 IdP 账号,并保留测试替换点。"""
_sync.sync_update_user(
user,
new_password=new_password,
set_password=casdoor_set_password,
add_user=casdoor_add_user,
)
@@ -0,0 +1,16 @@
"""
backend/app/services/auth/common/__init__.py
用途:导出不依赖 HXOPS 数据模型的认证公共类型。
依赖:common.identity。
逻辑:Casdoor 客户端、HXOPS 登录和 SSO 模块通过本入口共享统一身份对象。
"""
from .identity import AuthIdentity, IdentityValidationError, identity_key, require_stable_identity
__all__ = [
'AuthIdentity',
'IdentityValidationError',
'identity_key',
'require_stable_identity',
]
@@ -0,0 +1,69 @@
"""
backend/app/services/auth/common/identity.py
用途:定义跨认证来源通用、可复制的稳定身份对象。
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
"""
from __future__ import annotations
from dataclasses import dataclass
class IdentityValidationError(ValueError):
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
@dataclass(frozen=True)
class AuthIdentity:
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
issuer: str
subject: str
username: str
display_name: str | None = None
email: str | None = None
phone_number: str | None = None
employee_id: str | None = None
department: str | None = None
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
"""
校验跨服务身份必须具备 issuer、subject 和 username。
Args:
identity: 待校验的认证身份。
Returns:
去除稳定键首尾空白后的不可变身份对象。
Raises:
IdentityValidationError: 缺少稳定身份键或用户名。
"""
issuer = str(identity.issuer or '').strip()
subject = str(identity.subject or '').strip()
username = str(identity.username or '').strip()
if not issuer or not subject:
raise IdentityValidationError('Identity issuer and subject are required')
if not username:
raise IdentityValidationError('Identity username is required')
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
return identity
return AuthIdentity(
issuer=issuer,
subject=subject,
username=username,
display_name=identity.display_name,
email=identity.email,
phone_number=identity.phone_number,
employee_id=identity.employee_id,
department=identity.department,
)
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
stable = require_stable_identity(identity)
return stable.issuer, stable.subject
@@ -0,0 +1,20 @@
"""
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
__all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'issue_hxops_access_token',
'resolve_hxops_user',
]
@@ -0,0 +1,315 @@
"""
backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError
from app.models import User
from app.services.auth.casdoor.errors import clean_str, extract_error_payload, is_password_error
AddUserOperation = Callable[[dict[str, Any]], None]
SetPasswordOperation = Callable[[str, str, str, str], None]
def is_casdoor_configured() -> bool:
"""检查用户同步所需的 organization、地址和客户端凭据是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner,缺失时阻止构造无效用户请求。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def is_user_exists_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示用户名或用户记录已存在。"""
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_user_missing_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示 IdP 中不存在目标用户。"""
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
"""将 IdP 缺失用户转换为稳定业务错误,避免上层解析供应商文本。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,不包含任何密码。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': clean_str(real_name) or username,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _management_config() -> tuple[str, str, str, int]:
"""读取 Casdoor 管理 API 配置,返回地址、凭据和 HTTP 超时。"""
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '')
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
timeout = max(1, int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8))
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
return base, client_id, client_secret, timeout
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/add-user` 创建 IdP 用户。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/add-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor add-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/update-user` 更新 IdP 用户资料。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/update-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor update-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor `/api/set-password` 修改或由管理员覆盖用户密码。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/set-password',
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor set-password failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
add_user: AddUserOperation | None = None,
) -> None:
"""管理端创建 HXOPS 用户时同步 Casdoor;未配置 IdP 时保持原有跳过行为。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
(add_user or casdoor_add_user)(payload)
def sync_admin_set_password(
user: User,
new_password: str,
*,
set_password: SetPasswordOperation | None = None,
) -> None:
"""管理端无旧密码重设 Casdoor 密码,并将缺失用户转换为稳定错误。"""
if not is_casdoor_configured():
return
try:
(set_password or casdoor_set_password)(casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(
user: User,
*,
new_password: str | None = None,
set_password: SetPasswordOperation | None = None,
add_user: AddUserOperation | None = None,
) -> None:
"""同步管理端改密;IdP 缺失账号时用新密码补建,资料编辑仍不主动同步。"""
if not is_casdoor_configured() or not new_password:
return
try:
sync_admin_set_password(user, new_password, set_password=set_password)
except AppError as exc:
if exc.code != 'CASDOOR_USER_NOT_IN_IDP':
raise
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
add_user=add_user,
)
@@ -0,0 +1,196 @@
"""
backend/app/services/auth/hxops/login_service.py
用途:统一编排 HXOPS 的 Casdoor 密码登录、授权码登录和刷新流程。
依赖:Casdoor token/identity 公共模块、HXOPS 用户映射、HXOPS API Token。
逻辑:Casdoor token -> claims -> AuthIdentity -> HXOPS User -> 本地 API JWT;路由仅负责参数和事务边界。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from flask import current_app
from app.core.auth.jwt import _decode_jwt
from app.core.errors import AppError
from app.models import User
from app.services.auth.casdoor.client import CasdoorTokenResult
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError
from .session_token import issue_hxops_access_token
from .user_resolver import HxopsIdentityMappingError, resolve_hxops_user
TokenOperation = Callable[..., CasdoorTokenResult | dict[str, Any]]
UserinfoOperation = Callable[[str], dict[str, Any]]
AuditOperation = Callable[..., None]
@dataclass(frozen=True)
class LoginResult:
"""HXOPS 登录接口所需的用户、Token 和原响应有效期数据。"""
user: User
identity: AuthIdentity
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
def login_payload(self) -> dict[str, Any]:
"""生成与现有 password/code 登录接口完全一致的扁平响应。"""
return {
'id': self.user.id,
'username': self.user.username,
'role': self.user.role,
'default_agent_id': self.user.default_agent_id,
'feature_permissions': self.user.get_feature_permissions(),
'source': 'casdoor',
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def refresh_payload(self) -> dict[str, Any]:
"""生成与现有 refresh 接口完全一致的 Token 响应。"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def _normalize_token_result(source: CasdoorTokenResult | dict[str, Any]) -> CasdoorTokenResult:
"""兼容重构期间旧字典替身和新的 CasdoorTokenResult。"""
if isinstance(source, CasdoorTokenResult):
return source
data = dict(source or {})
access_token = str(data.get('access_token') or '')
if not access_token:
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=401)
return CasdoorTokenResult(
access_token=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=data,
)
class HxopsLoginService:
"""把公共 Casdoor 能力与 HXOPS 用户、审计和 API JWT 组合起来。"""
def __init__(
self,
*,
password_login: TokenOperation,
authorization_code_login: TokenOperation,
refresh_token: TokenOperation,
userinfo: UserinfoOperation,
write_login_audit: AuditOperation | None = None,
decode_id_token: Callable[[str], dict[str, Any]] = _decode_jwt,
):
"""
注入 Casdoor 操作和可选审计函数,便于路由兼容与单元测试。
Args:
password_login: 执行 password grant 的函数。
authorization_code_login: 执行 code grant 的函数。
refresh_token: 执行 refresh grant 的函数。
userinfo: 读取 Casdoor userinfo 的函数。
write_login_audit: HXOPS 登录审计函数;公共模块不感知请求对象。
decode_id_token: 现有 Casdoor JWKS 验证函数。
"""
self._password_login = password_login
self._authorization_code_login = authorization_code_login
self._refresh_token = refresh_token
self._userinfo = userinfo
self._write_login_audit = write_login_audit
self._decode_id_token = decode_id_token
def _identity_from_token(self, token: CasdoorTokenResult, *, prefer_id_token: bool) -> AuthIdentity:
"""优先验证 ID token,失败或缺失时回退 HTTPS userinfo。"""
claims: dict[str, Any] | None = None
if prefer_id_token and token.id_token:
try:
claims = self._decode_id_token(token.id_token)
except Exception:
claims = None
if claims is None:
claims = self._userinfo(token.access_token)
try:
return identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
except IdentityValidationError as exc:
current_app.logger.warning(
'[casdoor_login] invalid stable identity reason=%s claim_keys=%s',
str(exc),
sorted(str(key) for key in claims.keys()),
)
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
def _complete_login(
self,
token_source: CasdoorTokenResult | dict[str, Any],
*,
prefer_id_token: bool,
fallback_refresh_token: str | None = None,
audit_success: bool = False,
) -> LoginResult:
"""完成身份解析、本地用户映射和 HXOPS API Token 签发。"""
token = _normalize_token_result(token_source)
identity = self._identity_from_token(token, prefer_id_token=prefer_id_token)
try:
user = resolve_hxops_user(identity)
except HxopsIdentityMappingError as exc:
raise AppError(code=exc.code, message=str(exc), http_status=exc.status) from exc
if audit_success and self._write_login_audit:
self._write_login_audit('casdoor', 'success', user=user)
return LoginResult(
user=user,
identity=identity,
access_token=issue_hxops_access_token(user, identity),
refresh_token=token.refresh_token or fallback_refresh_token,
id_token=token.id_token,
token_type=token.token_type,
expires_in=token.expires_in,
)
def password(self, username: str, password: str) -> LoginResult:
"""通过 Casdoor password grant 登录 HXOPS。"""
return self._complete_login(
self._password_login(username, password),
prefer_id_token=True,
audit_success=True,
)
def authorization_code(self, code: str, redirect_uri: str) -> LoginResult:
"""通过 Casdoor authorization code 登录 HXOPS。"""
return self._complete_login(
self._authorization_code_login(code, redirect_uri),
prefer_id_token=True,
audit_success=True,
)
def refresh(self, refresh_token: str) -> LoginResult:
"""刷新 Casdoor token 后重新确认身份并签发 HXOPS API JWT。"""
return self._complete_login(
self._refresh_token(refresh_token),
prefer_id_token=False,
fallback_refresh_token=refresh_token,
)
@@ -0,0 +1,31 @@
"""
backend/app/services/auth/hxops/session_token.py
用途:为 HXOPS 本地 API 签发包含 Casdoor 稳定身份引用的会话 JWT。
依赖:User、AuthIdentity、app.core.auth.jwt 现有签发函数。
逻辑:保留现有 HS256 claims 和有效期;只调整调用边界,不改变 Token 契约。
"""
from __future__ import annotations
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.auth.common import AuthIdentity
def issue_hxops_access_token(user: User, identity: AuthIdentity | None = None) -> str:
"""
签发 HXOPS API 会话 JWT,保持重构前 claims 完全兼容。
Args:
user: 已映射并检查 active 的 HXOPS 用户。
identity: 可选 Casdoor 稳定身份;存在时写入 casdoor_iss/casdoor_sub。
Returns:
由 HXOPS SECRET_KEY 签名的本站 Bearer Token。
"""
return issue_local_access_token(
user,
casdoor_issuer=identity.issuer if identity else None,
casdoor_subject=identity.subject if identity else None,
)
@@ -0,0 +1,57 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:当前阶段保持原用户名优先、邮箱回退规则,并统一检查本地用户状态。
"""
from __future__ import annotations
from flask import current_app
from app.extensions import db
from app.models import User
from app.services.auth.common import AuthIdentity
class HxopsIdentityMappingError(Exception):
"""HXOPS 本地用户无法映射或状态不允许登录。"""
def __init__(self, message: str, *, code: str, status: int):
super().__init__(message)
self.code = code
self.status = status
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按现有规则将认证身份映射到 HXOPS 用户。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步到 HXOPS 或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity username=%s email=%s subject=%s',
identity.username,
identity.email,
identity.subject,
)
user = db.session.query(User).filter_by(username=identity.username).first()
if user is None and identity.email:
user = db.session.query(User).filter_by(email=identity.email).first()
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
code='CASDOOR_USER_NOT_FOUND',
status=403,
)
if user.status != 'active':
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
return user
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/services/auth/sso/__init__.py
Purpose: Export the reusable HXOPS-to-peer-service SSO signing surface.
Dependencies: application registry and assertion signing modules.
Flow: API routes import this package; peer services consume the documented assertion/JWKS contract.
"""
from .application_registry import SsoApplication, get_application, list_applications
from .assertion_service import build_jwks, issue_assertion
__all__ = [
'SsoApplication',
'build_jwks',
'get_application',
'issue_assertion',
'list_applications',
]
@@ -0,0 +1,149 @@
"""
backend/app/services/auth/sso/application_registry.py
Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions.
Dependencies: Flask configuration, JSON, URL parsing, and AppError.
Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from urllib.parse import urlparse
from flask import current_app
from app.core.errors import AppError, NotFoundError
_APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$')
@dataclass(frozen=True)
class SsoApplication:
"""Registered peer-service metadata safe for server-controlled SSO routing."""
key: str
display_name: str
login_url: str
callback_url: str
audience: str
enabled: bool = True
def public_payload(self) -> dict[str, str]:
"""Return fields safe for authenticated HXOPS navigation components."""
return {
'key': self.key,
'display_name': self.display_name,
'login_url': self.login_url,
}
def _validate_http_url(value: str, *, field: str) -> str:
"""
Validate an application URL from server configuration.
Args:
value: Absolute browser or callback URL.
field: Configuration field name used in diagnostics.
Returns:
Normalized URL without surrounding whitespace.
Raises:
AppError: URL is missing, malformed, or uses HTTP outside development/testing.
"""
normalized = str(value or '').strip()
parsed = urlparse(normalized)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'Invalid SSO application {field}',
http_status=503,
)
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'SSO application {field} must use HTTPS',
http_status=503,
)
return normalized
def list_applications() -> list[SsoApplication]:
"""
Parse the enabled SSO application registry from ``SSO_APPS_JSON``.
Returns:
Valid enabled application definitions.
Raises:
AppError: Configuration is invalid. Fail closed to avoid open redirects.
"""
if not bool(current_app.config.get('SSO_ENABLED', False)):
return []
raw = current_app.config.get('SSO_APPS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry is invalid',
http_status=503,
) from exc
if not isinstance(items, list):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry must be a JSON array',
http_status=503,
)
applications: list[SsoApplication] = []
seen_keys: set[str] = set()
seen_audiences: set[str] = set()
for item in items:
if not isinstance(item, dict) or not bool(item.get('enabled', True)):
continue
key = str(item.get('key') or '').strip().lower()
audience = str(item.get('audience') or key).strip()
display_name = str(item.get('display_name') or key).strip()
if (
not _APP_KEY_RE.fullmatch(key)
or not _APP_KEY_RE.fullmatch(audience.lower())
or audience != audience.lower()
or not display_name
):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application identity configuration is incomplete',
http_status=503,
)
if key in seen_keys or audience in seen_audiences:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application keys and audiences must be unique',
http_status=503,
)
applications.append(SsoApplication(
key=key,
display_name=display_name,
login_url=_validate_http_url(item.get('login_url'), field='login_url'),
callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'),
audience=audience,
enabled=True,
))
seen_keys.add(key)
seen_audiences.add(audience)
return applications
def get_application(app_key: str) -> SsoApplication:
"""Resolve one enabled application by its server-controlled key."""
normalized = str(app_key or '').strip().lower()
for application in list_applications():
if application.key == normalized:
return application
raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')
@@ -0,0 +1,265 @@
"""
backend/app/services/auth/sso/assertion_service.py
Purpose: Sign peer-service-specific short-lived login assertions and publish their verification key.
Dependencies: application registry, PyJWT, cryptography, Flask configuration, and User.
Flow: The SSO API authenticates an HXOPS user, this module signs an audience-bound JWT, and peers verify it through JWKS.
"""
from __future__ import annotations
import base64
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import current_app
from app.core.errors import AppError, ValidationError
from app.models import User
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from .application_registry import get_application
def _config_error(message: str) -> AppError:
"""Build a fail-closed SSO configuration error without leaking key material."""
return AppError(code='AUTH.SSO_CONFIG_ERROR', message=message, http_status=503)
def _read_signing_key() -> rsa.RSAPrivateKey:
"""
Load the configured RSA private key used only for product SSO assertions.
Returns:
Parsed RSA private key.
Raises:
AppError: The path is absent, unreadable, invalid, or not an RSA private key.
"""
raw_path = str(current_app.config.get('SSO_PRIVATE_KEY_PATH') or '').strip()
if not raw_path:
raise _config_error('SSO signing private key is not configured')
try:
key_bytes = Path(raw_path).read_bytes()
private_key = serialization.load_pem_private_key(key_bytes, password=None)
except (OSError, ValueError, TypeError) as exc:
raise _config_error('SSO signing private key cannot be loaded') from exc
if not isinstance(private_key, rsa.RSAPrivateKey):
raise _config_error('SSO signing key must be an RSA private key')
return private_key
def _issuer() -> str:
"""Return the configured absolute SSO issuer after environment-aware URL validation."""
issuer = str(current_app.config.get('SSO_ISSUER') or '').strip().rstrip('/')
parsed = urlparse(issuer)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise _config_error('SSO issuer must be an absolute URL')
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise _config_error('SSO issuer must use HTTPS')
return issuer
def _ttl_seconds() -> int:
"""Validate the short assertion lifetime; values outside 10-60 seconds fail closed."""
try:
ttl_seconds = int(current_app.config.get('SSO_ASSERTION_TTL_SECONDS') or 60)
except (TypeError, ValueError) as exc:
raise _config_error('SSO assertion TTL is invalid') from exc
if ttl_seconds < 10 or ttl_seconds > 60:
raise _config_error('SSO assertion TTL must be between 10 and 60 seconds')
return ttl_seconds
def _algorithm() -> str:
"""Enforce the single supported asymmetric signing algorithm and reject downgrade configuration."""
algorithm = str(current_app.config.get('SSO_SIGNING_ALGORITHM') or 'RS256').strip().upper()
if algorithm != 'RS256':
raise _config_error('SSO signing algorithm must be RS256')
return algorithm
def _key_id() -> str:
"""Return the stable public key identifier embedded in JWT and JWKS metadata."""
key_id = str(current_app.config.get('SSO_SIGNING_KEY_ID') or '').strip()
if not key_id or len(key_id) > 128:
raise _config_error('SSO signing key ID is not configured')
return key_id
def _identity_claims(user: User, claims: dict[str, Any]) -> dict[str, Any]:
"""
Build the portable Casdoor identity claims without HXOPS business permissions.
Args:
user: Active HXOPS user mapped from the authenticated Casdoor identity.
claims: Verified HXOPS API JWT claims containing ``casdoor_iss/casdoor_sub``.
Returns:
Stable identity plus mutable display attributes safe for peer-service user mapping.
"""
expected_issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
try:
identity = identity_from_claims({
'iss': claims.get('casdoor_iss'),
'sub': claims.get('casdoor_sub'),
'preferred_username': user.username,
'name': user.real_name or user.username,
'email': user.email,
'phone_number': user.phone_number,
'employee_id': user.employee_id,
'department': user.department,
}, expected_issuer=expected_issuer)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.SSO_IDENTITY_UNSUPPORTED',
message='Current login is not backed by a Casdoor identity',
http_status=403,
) from exc
return {
'sub': identity.subject,
'identity_issuer': identity.issuer,
'preferred_username': identity.username,
'name': identity.display_name,
'email': identity.email,
'phone_number': identity.phone_number,
'employee_id': identity.employee_id,
'department': identity.department,
}
def issue_assertion(*, app_key: str, user: User, claims: dict[str, Any], state: Any) -> dict[str, Any]:
"""
Sign a peer-service-specific login assertion for an active HXOPS user.
Args:
app_key: Server-registered target service key.
user: Current active HXOPS user.
claims: Verified HXOPS API JWT claims with Casdoor identity references.
state: Opaque signed state created by the peer service and returned unchanged.
Returns:
Registered callback URL, RS256 assertion, original state, and expiry seconds.
"""
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
normalized_state = str(state or '').strip()
if not normalized_state or len(normalized_state) > 4096:
raise ValidationError('state is required and must not exceed 4096 characters')
application = get_application(app_key)
ttl_seconds = _ttl_seconds()
now = datetime.now(timezone.utc)
payload = {
'iss': _issuer(),
'aud': application.audience,
**_identity_claims(user, claims),
'iat': int(now.timestamp()),
'nbf': int((now - timedelta(seconds=5)).timestamp()),
'exp': int((now + timedelta(seconds=ttl_seconds)).timestamp()),
'jti': secrets.token_urlsafe(24),
}
try:
assertion = jwt.encode(
payload,
_read_signing_key(),
algorithm=_algorithm(),
headers={'kid': _key_id(), 'typ': 'JWT'},
)
except AppError:
raise
except Exception as exc:
current_app.logger.exception('[sso] failed to sign assertion app=%s', application.key)
raise AppError(
code='AUTH.SSO_ASSERTION_ISSUE_FAILED',
message='Failed to issue an SSO assertion',
http_status=503,
retryable=True,
) from exc
current_app.logger.info(
'[sso] assertion issued app=%s user_id=%s subject=%s ttl=%s',
application.key,
user.id,
payload['sub'],
ttl_seconds,
)
return {
'post_url': application.callback_url,
'assertion': assertion,
'state': normalized_state,
'expires_in': ttl_seconds,
}
def _base64url_uint(value: int) -> str:
"""Encode an RSA integer using the unpadded base64url form required by JWK."""
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
def _public_jwk(public_key: rsa.RSAPublicKey, *, key_id: str) -> dict[str, str]:
"""Convert one trusted RSA public key to the minimal signing JWK contract."""
numbers = public_key.public_numbers()
return {
'kty': 'RSA',
'kid': key_id,
'use': 'sig',
'alg': _algorithm(),
'n': _base64url_uint(numbers.n),
'e': _base64url_uint(numbers.e),
}
def _additional_public_jwks(active_key_id: str) -> list[dict[str, str]]:
"""
Load verification-only public keys retained during a signing-key rotation window.
Returns:
Additional JWK entries configured as ``[{"kid", "public_key_path"}]``.
Raises:
AppError: JSON, key IDs, paths, or public key material are invalid.
"""
raw = current_app.config.get('SSO_ADDITIONAL_PUBLIC_KEYS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise _config_error('Additional SSO public keys configuration is invalid') from exc
if not isinstance(items, list):
raise _config_error('Additional SSO public keys must be a JSON array')
jwks: list[dict[str, str]] = []
seen_key_ids = {active_key_id}
for item in items:
if not isinstance(item, dict):
raise _config_error('Additional SSO public key entry is invalid')
key_id = str(item.get('kid') or '').strip()
path = str(item.get('public_key_path') or '').strip()
if not key_id or len(key_id) > 128 or not path or key_id in seen_key_ids:
raise _config_error('Additional SSO public key identity is invalid or duplicated')
try:
public_key = serialization.load_pem_public_key(Path(path).read_bytes())
except (OSError, ValueError, TypeError) as exc:
raise _config_error('Additional SSO public key cannot be loaded') from exc
if not isinstance(public_key, rsa.RSAPublicKey):
raise _config_error('Additional SSO public key must be RSA')
jwks.append(_public_jwk(public_key, key_id=key_id))
seen_key_ids.add(key_id)
return jwks
def build_jwks() -> dict[str, list[dict[str, str]]]:
"""Build JWKS with the active signing key plus verification-only rotation keys."""
active_key_id = _key_id()
active_jwk = _public_jwk(_read_signing_key().public_key(), key_id=active_key_id)
return {'keys': [active_jwk, *_additional_public_jwks(active_key_id)]}
@@ -8,6 +8,7 @@ tests/test_admin_create_user_casdoor.py
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.api import user as user_api
from app.services.auth import casdoor_service
@@ -24,6 +25,21 @@ NEW_USER_PAYLOAD = {
}
@pytest.fixture
def admin_headers(app):
"""为 Casdoor 用户同步接口生成真实 HXOPS 管理员 JWT,避免依赖旧认证请求头。"""
app.config['SECRET_KEY'] = 'test-casdoor-sync-secret-at-least-32-bytes'
admin = User(username='casdoor-sync-admin', email='casdoor-sync-admin@example.com', role='admin', status='active')
admin.set_password('test-admin-password')
db.session.add(admin)
db.session.commit()
token = issue_local_access_token(admin)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
"""
Casdoor 已配置时,管理端创建用户应调用 add-user 且本地库成功入库。
+177
View File
@@ -0,0 +1,177 @@
"""
backend/tests/test_auth_common.py
用途:验证可复制认证公共模块的身份、配置、Casdoor HTTP 请求和错误安全边界。
依赖:pytest、Flask 测试应用、公共 auth common/casdoor 模块。
逻辑:不访问 HXOPS User 表,确保公共目录可以脱离业务模型独立工作。
"""
from __future__ import annotations
import pytest
from app.core.errors import AppError
from app.services.auth.casdoor.client import CasdoorClient, get_casdoor_client
from app.services.auth.casdoor.config import CasdoorConfig, casdoor_config_from_flask
from app.services.auth.casdoor.errors import raise_auth_error
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError, identity_key
class FakeResponse:
"""提供 CasdoorClient 单测所需的最小 requests.Response 行为。"""
def __init__(self, data, *, ok=True, status_code=200):
self._data = data
self.ok = ok
self.status_code = status_code
def json(self):
"""返回构造时注入的 JSON 数据。"""
return self._data
def raise_for_status(self):
"""模拟 discovery 请求的 HTTP 状态检查。"""
if not self.ok:
raise RuntimeError(f'HTTP {self.status_code}')
class FakeHttp:
"""记录 CasdoorClient 请求,避免单测访问真实 Casdoor。"""
def __init__(self):
self.posts = []
self.gets = []
def get(self, url, **kwargs):
"""按 URL 返回 discovery 或 userinfo 测试响应。"""
self.gets.append((url, kwargs))
if url.endswith('/.well-known/openid-configuration'):
return FakeResponse({
'token_endpoint': 'https://casdoor.test/token',
'userinfo_endpoint': 'https://casdoor.test/userinfo',
})
return FakeResponse({
'iss': 'https://casdoor.test',
'sub': 'subject-1',
'preferred_username': 'alice',
})
def post(self, url, **kwargs):
"""记录 token 请求并返回固定 token 集合。"""
self.posts.append((url, kwargs))
return FakeResponse({
'access_token': 'casdoor-access',
'refresh_token': 'casdoor-refresh',
'token_type': 'Bearer',
'expires_in': 3600,
})
def test_identity_key_requires_stable_identity():
"""公共身份必须使用 issuer + subject 作为稳定键,不能接受缺失 subject 的资料。"""
identity = AuthIdentity(issuer='https://casdoor.test', subject='subject-1', username='alice')
assert identity_key(identity) == ('https://casdoor.test', 'subject-1')
with pytest.raises(IdentityValidationError):
identity_key(AuthIdentity(issuer='https://casdoor.test', subject='', username='alice'))
def test_identity_from_claims_validates_issuer_and_normalizes_fields():
"""Casdoor claims 转换后保留稳定身份和可变资料,并拒绝错误 issuer。"""
identity = identity_from_claims({
'iss': 'https://casdoor.test/',
'sub': 'subject-1',
'preferred_username': 'alice',
'displayName': 'Alice Zhang',
'email': 'alice@example.com',
'affiliation': 'IT',
}, expected_issuer='https://casdoor.test')
assert identity.username == 'alice'
assert identity.display_name == 'Alice Zhang'
assert identity.department == 'IT'
with pytest.raises(IdentityValidationError):
identity_from_claims({
'iss': 'https://evil.test',
'sub': 'subject-1',
'preferred_username': 'alice',
}, expected_issuer='https://casdoor.test')
def test_identity_from_claims_uses_configured_issuer_when_userinfo_omits_iss():
"""Casdoor userinfo 可省略 iss,但服务端可信 issuer 仍必须来自 discovery 对齐配置。"""
identity = identity_from_claims({
'sub': 'subject-1',
'preferred_username': 'alice',
}, expected_issuer='https://casdoor.test')
assert identity.issuer == 'https://casdoor.test'
assert identity.subject == 'subject-1'
def test_casdoor_config_repr_does_not_expose_secret(app):
"""配置对象可诊断但不得在 repr 中泄漏 Casdoor client_secret。"""
app.config.update(
CASDOOR_BASE_URL='https://casdoor.test/',
CASDOOR_CLIENT_ID='peer-client',
CASDOOR_CLIENT_SECRET='top-secret-value',
AUTH_JWT_ISSUER='https://casdoor.test',
CASDOOR_SCOPE='openid profile email',
CASDOOR_HTTP_TIMEOUT_SECONDS=9,
)
config = casdoor_config_from_flask()
assert config.base_url == 'https://casdoor.test'
assert config.timeout_seconds == 9
assert 'top-secret-value' not in repr(config)
def test_casdoor_password_client_request_is_framework_independent():
"""公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。"""
http = FakeHttp()
client = CasdoorClient(CasdoorConfig(
base_url='https://casdoor.test',
client_id='peer-client',
client_secret='peer-secret',
issuer='https://casdoor.test',
timeout_seconds=7,
), http_session=http)
result = client.password_login('alice', 'user-password')
assert result.access_token == 'casdoor-access'
_, request = http.posts[0]
assert request['data']['grant_type'] == 'password'
assert request['data']['client_id'] == 'peer-client'
assert request['data']['password'] == 'user-password'
assert request['timeout'] == 7
def test_flask_casdoor_client_is_reused_until_config_changes(app):
"""Flask 适配器复用 discovery 缓存,并在服务配置变化后创建新客户端。"""
app.config.update(
CASDOOR_BASE_URL='https://casdoor.test',
CASDOOR_CLIENT_ID='peer-client-cache',
CASDOOR_CLIENT_SECRET='peer-secret-cache',
AUTH_JWT_ISSUER='https://casdoor.test',
CASDOOR_HTTP_TIMEOUT_SECONDS=8,
)
first = get_casdoor_client()
second = get_casdoor_client()
assert first is second
app.config['CASDOOR_CLIENT_ID'] = 'peer-client-changed'
third = get_casdoor_client()
assert third is not first
@pytest.mark.parametrize(
('source', 'context', 'code', 'status'),
[
({'error': 'invalid_grant'}, 'password', 'CASDOOR_INVALID_CREDENTIALS', 401),
({'error': 'invalid_client'}, 'password', 'CASDOOR_CONFIG_ERROR', 503),
({'error': 'access_denied'}, 'code', 'CASDOOR_ACCESS_DENIED', 403),
({'error': 'unsupported_grant_type'}, 'refresh', 'AUTH.CASDOOR_REFRESH_UNSUPPORTED', 400),
],
)
def test_casdoor_error_mapping_is_stable(app, source, context, code, status):
"""公共错误映射保持现有 HXOPS 业务码,供平级服务复制后统一处理。"""
with pytest.raises(AppError) as captured:
raise_auth_error(source, context=context)
assert captured.value.code == code
assert captured.value.http_status == status
+167
View File
@@ -0,0 +1,167 @@
"""
backend/tests/test_casdoor_api_session.py
用途:验证 Casdoor 认证成功后返回 HXOPS 本地 API 会话 JWT,并保留稳定 Casdoor 身份引用。
依赖:Flask 测试客户端、User 模型、user API 的 Casdoor 调用替身。
逻辑:模拟 password grant/userinfo,随后使用返回 token 访问受保护 API,防止登录后首个请求立即 401。
"""
from __future__ import annotations
import jwt
import pytest
from app import db
from app.api import user as user_api
from app.core.errors import AppError
from app.models import User
@pytest.fixture
def casdoor_user(app):
"""创建能被 Casdoor userinfo 映射的 active HXOPS 用户。"""
user = User(username='casdoor-session', email='casdoor-session@example.com', role='user', status='active')
db.session.add(user)
db.session.commit()
return user
def test_password_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
"""密码由 Casdoor 校验,但浏览器使用 HXOPS 签名 JWT 调用本站 API。"""
app.config.update(
AUTH_LOGIN_MODE='casdoor',
AUTH_JWT_ISSUER='https://casdoor.example.com',
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
AUTH_ALLOW_LOCAL_JWT=True,
SECRET_KEY='test-session-secret',
)
monkeypatch.setattr(user_api, '_casdoor_password_login', lambda username, password: {
'access_token': 'opaque-casdoor-access-token',
'refresh_token': 'casdoor-refresh-token',
'expires_in': 3600,
})
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-session',
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
login = client.post('/api/user/casdoor/password-login', json={
'username': casdoor_user.username,
'password': 'correct-password',
})
assert login.status_code == 200
body = login.get_json()
data = body.get('data') if body.get('success') is True else body
api_token = data['access_token']
assert api_token != 'opaque-casdoor-access-token'
claims = jwt.decode(
api_token,
app.config['SECRET_KEY'],
algorithms=['HS256'],
issuer='hxops-backend',
audience='hxops-frontend',
)
assert claims['casdoor_iss'] == 'https://casdoor.example.com'
assert claims['casdoor_sub'] == 'casdoor-subject-session'
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
assert home.status_code == 200
def test_authorization_code_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
"""授权码回调复用统一登录编排,并签发可访问 HXOPS API 的本地 JWT。"""
app.config.update(
AUTH_JWT_ISSUER='https://casdoor.example.com',
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
AUTH_ALLOW_LOCAL_JWT=True,
SECRET_KEY='test-code-session-secret-at-least-32-bytes',
)
monkeypatch.setattr(user_api, '_casdoor_exchange_code', lambda code, redirect_uri: {
'access_token': 'code-opaque-casdoor-access-token',
'refresh_token': 'code-casdoor-refresh-token',
'expires_in': 3600,
})
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-code-session',
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
with app.app_context():
state = user_api._issue_casdoor_state('https://hxops.example.com/auth/callback')
login = client.post('/api/user/casdoor/login', json={
'code': 'authorization-code',
'state': state,
})
assert login.status_code == 200
body = login.get_json()
data = body.get('data') if body.get('success') is True else body
assert data['refresh_token'] == 'code-casdoor-refresh-token'
claims = jwt.decode(
data['access_token'],
app.config['SECRET_KEY'],
algorithms=['HS256'],
issuer='hxops-backend',
audience='hxops-frontend',
)
assert claims['casdoor_sub'] == 'casdoor-subject-code-session'
home = client.get('/api/user/home', headers={'Authorization': f"Bearer {data['access_token']}"})
assert home.status_code == 200
def test_refresh_returns_new_hxops_api_session(client, app, casdoor_user, monkeypatch):
"""Casdoor refresh 成功后重新映射用户并签发新的 HXOPS API 会话。"""
app.config.update(
AUTH_JWT_ISSUER='https://casdoor.example.com',
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
AUTH_ALLOW_LOCAL_JWT=True,
SECRET_KEY='test-session-secret-at-least-32-bytes',
)
monkeypatch.setattr(user_api, '_casdoor_refresh_token', lambda refresh_token: {
'access_token': 'next-opaque-casdoor-access-token',
'refresh_token': 'next-casdoor-refresh-token',
'expires_in': 3600,
})
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-session',
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
refreshed = client.post('/api/user/casdoor/refresh', json={
'refresh_token': 'old-casdoor-refresh-token',
})
assert refreshed.status_code == 200
body = refreshed.get_json()
data = body.get('data') if body.get('success') is True else body
api_token = data['access_token']
assert api_token != 'next-opaque-casdoor-access-token'
assert data['refresh_token'] == 'next-casdoor-refresh-token'
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
assert home.status_code == 200
def test_refresh_preserves_structured_casdoor_error(client, monkeypatch):
"""刷新 grant 的稳定 AppError 应原样返回,不能被路由兜底包装成通用 401。"""
def unsupported_refresh(_refresh_token):
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
)
monkeypatch.setattr(user_api, '_casdoor_refresh_token', unsupported_refresh)
response = client.post('/api/user/casdoor/refresh', json={'refresh_token': 'unsupported-token'})
assert response.status_code == 400
assert response.get_json()['error']['code'] == 'AUTH.CASDOOR_REFRESH_UNSUPPORTED'
+316
View File
@@ -0,0 +1,316 @@
"""
backend/tests/test_sso.py
用途:验证 HXOPS 面向产品内平级服务的 RS256 assertion、应用注册表和 JWKS 契约。
依赖:Flask 测试客户端、User、PyJWT、cryptography 与临时 RSA 密钥。
逻辑:模拟带 Casdoor 身份引用的 HXOPS 会话,断言 JWT 受众、有效期、身份字段和公钥发布均符合协议。
"""
from __future__ import annotations
import json
import jwt
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import g
from app import db
from app.models import User
@pytest.fixture
def active_user(app):
"""创建可签发平级服务登录 assertion 的 active HXOPS 用户。"""
user = User(
username='sso-user',
email='sso-user@example.com',
real_name='SSO User',
employee_id='E1001',
phone_number='13800000001',
department='IT',
role='user',
status='active',
)
db.session.add(user)
db.session.commit()
return user
@pytest.fixture
def sso_keys(tmp_path):
"""生成仅供当前测试使用的当前私钥、旧公钥文件和公钥对象。"""
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_key_path = tmp_path / 'hxops-sso-private.pem'
private_key_path.write_bytes(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
))
old_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
old_public_key_path = tmp_path / 'hxops-sso-old-public.pem'
old_public_key_path.write_bytes(old_private_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
))
return private_key_path, private_key.public_key(), old_public_key_path
@pytest.fixture
def sso_config(app, sso_keys):
"""启用一个使用测试地址和独立 audience 的产品内平级服务。"""
private_key_path, public_key, old_public_key_path = sso_keys
app.config.update(
SSO_ENABLED=True,
ENV_NAME='test',
AUTH_JWT_ISSUER='https://casdoor.example.com',
SSO_ASSERTION_TTL_SECONDS=60,
SSO_ISSUER='http://hxops.test',
SSO_SIGNING_ALGORITHM='RS256',
SSO_SIGNING_KEY_ID='hxops-sso-test-key',
SSO_PRIVATE_KEY_PATH=str(private_key_path),
SSO_ADDITIONAL_PUBLIC_KEYS_JSON=json.dumps([{
'kid': 'hxops-sso-old-key',
'public_key_path': str(old_public_key_path),
}]),
SSO_APPS_JSON=json.dumps([{
'key': 'peer-service',
'display_name': 'Peer Service',
'login_url': 'http://peer.test/auth/hxops/start',
'callback_url': 'http://peer.test/auth/hxops/callback',
'audience': 'peer-service',
'enabled': True,
}]),
)
return public_key
def _bearer_user(monkeypatch, user, *, claims=None):
"""模拟已验证 HXOPS API JWT,并把 Casdoor 稳定身份引用挂到 Flask g。"""
resolved_claims = claims if claims is not None else {
'casdoor_iss': 'https://casdoor.example.com',
'casdoor_sub': 'casdoor-subject-1001',
}
def resolve_user():
g.jwt_claims = resolved_claims
return user
monkeypatch.setattr('app.api.sso.get_current_user', resolve_user)
def _data(response):
"""兼容是否启用成功 envelope,提取实际 API 数据。"""
body = response.get_json()
return body.get('data') if body.get('success') is True else body
def _error_code(response):
"""从统一错误 envelope 中提取业务错误码。"""
return (response.get_json().get('error') or {}).get('code')
def _issue(client, monkeypatch, user, *, state='peer-signed-state'):
"""签发一枚测试 assertion,供声明与错误分支测试复用。"""
_bearer_user(monkeypatch, user)
return client.post(
'/api/sso/apps/peer-service/assertions',
headers={'Authorization': 'Bearer verified-token'},
json={'state': state},
)
def test_apps_requires_bearer_header(client, sso_config):
"""平级服务目录不接受匿名请求或 legacy 用户头。"""
response = client.get('/api/sso/apps')
assert response.status_code == 401
assert _error_code(response) == 'AUTH.UNAUTHORIZED'
def test_assertion_is_rs256_audience_bound_and_contains_no_permissions(
client,
active_user,
sso_config,
monkeypatch,
):
"""签发结果可被公开密钥验证,且只包含共享身份、不包含 HXOPS 权限。"""
response = _issue(client, monkeypatch, active_user)
assert response.status_code == 200
result = _data(response)
assert result['post_url'] == 'http://peer.test/auth/hxops/callback'
assert result['state'] == 'peer-signed-state'
assert result['expires_in'] == 60
header = jwt.get_unverified_header(result['assertion'])
assert header['alg'] == 'RS256'
assert header['kid'] == 'hxops-sso-test-key'
claims = jwt.decode(
result['assertion'],
sso_config,
algorithms=['RS256'],
issuer='http://hxops.test',
audience='peer-service',
)
# 关键断言:稳定 Casdoor 身份进入 token,本地用户主键和业务权限不得泄漏。
assert claims['sub'] == 'casdoor-subject-1001'
assert claims['identity_issuer'] == 'https://casdoor.example.com'
assert claims['preferred_username'] == active_user.username
assert claims['name'] == active_user.real_name
assert claims['exp'] - claims['iat'] == 60
assert claims['nbf'] <= claims['iat']
assert claims['jti']
assert 'user_id' not in claims
assert 'role' not in claims
assert 'feature_permissions' not in claims
def test_each_assertion_has_a_unique_jti(client, active_user, sso_config, monkeypatch):
"""同一用户连续签发的 assertion 使用不同 jti,便于平级服务按需增加防重放。"""
first = _data(_issue(client, monkeypatch, active_user))['assertion']
second = _data(_issue(client, monkeypatch, active_user))['assertion']
first_claims = jwt.decode(first, sso_config, algorithms=['RS256'], audience='peer-service')
second_claims = jwt.decode(second, sso_config, algorithms=['RS256'], audience='peer-service')
assert first_claims['jti'] != second_claims['jti']
def test_jwks_publishes_matching_public_key(client, sso_config):
"""公开 JWKS 同时发布当前和旧公钥,且响应不包含任何私钥参数。"""
response = client.get('/.well-known/jwks.json')
assert response.status_code == 200
body = _data(response)
assert response.headers['Cache-Control'] == 'public, max-age=300'
assert len(body['keys']) == 2
jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-test-key')
old_jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-old-key')
assert jwk['kid'] == 'hxops-sso-test-key'
assert jwk['alg'] == 'RS256'
assert jwk['kty'] == 'RSA'
assert jwk['use'] == 'sig'
assert jwk['n']
assert jwk['e'] == 'AQAB'
assert old_jwk['alg'] == 'RS256'
assert old_jwk['n'] != jwk['n']
assert 'd' not in jwk
assert 'p' not in jwk
assert 'q' not in jwk
def test_assertion_requires_casdoor_identity(client, active_user, sso_config, monkeypatch):
"""缺少 casdoor_iss/casdoor_sub 的 HXOPS 本地登录态不能跨服务签发身份。"""
_bearer_user(monkeypatch, active_user, claims={'username': active_user.username})
response = client.post(
'/api/sso/apps/peer-service/assertions',
headers={'Authorization': 'Bearer local-token'},
json={'state': 'peer-signed-state'},
)
assert response.status_code == 403
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
def test_local_issuer_subject_cannot_impersonate_casdoor(
client,
active_user,
sso_config,
monkeypatch,
):
"""HXOPS API JWT 自身的标准 iss/sub 不能冒充 Casdoor 身份引用。"""
_bearer_user(monkeypatch, active_user, claims={
'iss': 'hxops-backend',
'sub': str(active_user.id),
})
response = client.post(
'/api/sso/apps/peer-service/assertions',
headers={'Authorization': 'Bearer local-token'},
json={'state': 'peer-signed-state'},
)
assert response.status_code == 403
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
@pytest.mark.parametrize('state', ['', 'x' * 4097])
def test_assertion_rejects_invalid_state(client, active_user, sso_config, monkeypatch, state):
"""state 必须存在且受长度限制,避免放大请求或意外持久化不可信数据。"""
response = _issue(client, monkeypatch, active_user, state=state)
assert response.status_code == 400
assert _error_code(response) == 'VALIDATION.INVALID_PARAM'
def test_assertion_rejects_unknown_application(client, active_user, sso_config, monkeypatch):
"""浏览器不能通过未注册 app key 指定任意 callback 或 audience。"""
_bearer_user(monkeypatch, active_user)
response = client.post(
'/api/sso/apps/not-registered/assertions',
headers={'Authorization': 'Bearer verified-token'},
json={'state': 'peer-signed-state'},
)
assert response.status_code == 404
assert _error_code(response) == 'AUTH.SSO_APP_NOT_FOUND'
def test_application_registry_rejects_duplicate_audience(client, app, active_user, sso_config, monkeypatch):
"""两个平级服务不能共享 audience,避免一个服务接受签给另一个服务的 assertion。"""
app.config['SSO_APPS_JSON'] = json.dumps([
{
'key': 'peer-service-a',
'display_name': 'Peer Service A',
'login_url': 'http://peer-a.test/auth/hxops/start',
'callback_url': 'http://peer-a.test/auth/hxops/callback',
'audience': 'shared-audience',
},
{
'key': 'peer-service-b',
'display_name': 'Peer Service B',
'login_url': 'http://peer-b.test/auth/hxops/start',
'callback_url': 'http://peer-b.test/auth/hxops/callback',
'audience': 'shared-audience',
},
])
_bearer_user(monkeypatch, active_user)
response = client.get('/api/sso/apps', headers={'Authorization': 'Bearer verified-token'})
assert response.status_code == 503
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
@pytest.mark.parametrize(
('config_key', 'config_value'),
[
('SSO_ASSERTION_TTL_SECONDS', 61),
('SSO_SIGNING_ALGORITHM', 'HS256'),
('SSO_PRIVATE_KEY_PATH', ''),
],
)
def test_assertion_fails_closed_for_invalid_signing_config(
client,
app,
active_user,
sso_config,
monkeypatch,
config_key,
config_value,
):
"""TTL、算法或私钥配置错误时返回 503,不使用普通 API JWT 密钥降级。"""
app.config[config_key] = config_value
response = _issue(client, monkeypatch, active_user)
assert response.status_code == 503
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
def test_jwks_fails_closed_for_duplicate_rotation_key_id(client, app, sso_config):
"""旧验证公钥不得复用当前 kid,避免平级服务选择到含义不明确的公钥。"""
app.config['SSO_ADDITIONAL_PUBLIC_KEYS_JSON'] = json.dumps([{
'kid': 'hxops-sso-test-key',
'public_key_path': 'unused',
}])
response = client.get('/.well-known/jwks.json', headers={'Accept': 'application/json'})
assert response.status_code == 503
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
def test_legacy_ticket_and_exchange_routes_are_removed(client, sso_config):
"""旧 Redis ticket 协议路由必须彻底下线,避免两个认证契约并存。"""
ticket_response = client.post('/api/sso/apps/peer-service/tickets')
exchange_response = client.post('/api/sso/exchange')
assert ticket_response.status_code == 404
assert exchange_response.status_code == 404
+14
View File
@@ -453,3 +453,17 @@
- 抬头字段仅用于内部区域划分和排除误报,不在 Chat 结果中展示,也不计入条款改动;正文严格比对;签章区域排除;签章后的附件仅提示新增或减少页数。
- 附件内容不进入差异清单、改动总数或风险统计;两侧附件页数相同即不提示内容差异。
- 无默认模板、无配置、分页提取失败或正文锚点识别失败时,安全回退全文比对并向用户展示警告。
# HXOPS 与产品内平级服务统一认证(2026-07-27)
- HXOPS 是用户管理入口,继续负责用户增删改查和密码修改,并将用户及密码变更同步到 Casdoor;平级服务不提供用户和密码维护入口。
- HXOPS 与平级服务共用 Casdoor 用户和密码。HXOPS 保留现有登录页,由后端调用 Casdoor 校验,用户不进入 Casdoor 登录页。
- 平级服务可以保留自己的登录页;其后端使用独立 Casdoor Application 校验同一套账号密码,成功后建立平级服务自己的 Session,不依赖 HXOPS 登录态。
- 用户从 HXOPS 点击平级服务入口时,HXOPS 签发面向目标服务、有效期不超过 60 秒的专用 JWT,并通过表单 POST 完成无感登录,不再次输入账号密码。
- 平级服务可以提供“使用 HXOPS 登录”和“返回 HXOPS”入口;HXOPS 未登录时先显示 HXOPS 登录页,成功后自动返回平级服务原页面。
- 无感登录目标方案不依赖 Redis,不传递 HXOPS API JWT、Casdoor token 或用户密码,也不调用票据兑换接口。
- 本期只建设认证、跳转和共享身份契约,不处理企业微信登录、拒绝用户清理、跨服务业务权限同步和全局单点退出。
- HXOPS 已按无状态短时 JWT 方案移除 Redis 一次性票据接口;平级服务侧按 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md) 实现独立登录、JWT 验签和本地 Session。
- 认证代码先完成结构重构并提取可复制公共部分,不制作依赖包;重构不得改变现有认证协议、接口路径、响应格式、JWT 声明/有效期或数据库结构。
---
+1
View File
@@ -4,6 +4,7 @@
| 域 | 说明 | 入口 |
| --- | --- | --- |
| [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) |
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) |
| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) |
| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) |
+6
View File
@@ -0,0 +1,6 @@
# 认证与单点登录
HXOPS 与产品内平级服务共用 Casdoor 用户和密码。平级服务可以保留自己的登录页;从 HXOPS 进入时使用目标服务专用短时 JWT 完成无感登录。
- [HXOPS 产品内平级服务统一认证技术方案](hxops-peer-service-sso.md)
- [已废弃:外部第三方一次性票据方案](hxops-third-party-sso.md)
@@ -0,0 +1,622 @@
# HXOPS 产品内平级服务统一认证技术方案
## 1. 文档目的
本文定义 HXOPS 与同一套产品下平级服务之间的统一认证方案。
平级服务不是对外开放的第三方应用,而是与 HXOPS 处于同一产品、同一用户体系和同一运维边界内的独立服务。目标是在保留平级服务独立登录能力的同时,实现从 HXOPS 进入平级服务时的无感登录。
本文是当前 HXOPS 实现及平级服务接入的权威方案。HXOPS 已移除一次性票据与 Redis 兑换实现,并切换为本文定义的 assertion/JWKS 协议;平级服务代码库按本文契约完成接入。
## 2. 业务目标
### 2.1 用户体验
1. 用户在 HXOPS 登录页输入账号密码,由 HXOPS 后端通过 Casdoor 完成认证。
2. 用户登录 HXOPS 后点击平级服务入口,新标签页直接进入平级服务,不再次输入账号密码。
3. 用户直接访问平级服务时,可以在平级服务自己的登录页使用同一套账号密码登录。
4. 平级服务可以提供“使用 HXOPS 登录”入口;若 HXOPS 已登录则直接返回,未登录则先进入 HXOPS 登录页。
5. 平级服务可以提供返回 HXOPS 的链接,HXOPS 登录态有效时直接进入。
### 2.2 用户管理边界
- 用户新增、修改、禁用、删除和密码修改只在 HXOPS 操作。
- HXOPS 负责将用户及密码变化同步到 Casdoor。
- 平级服务不提供用户和密码维护入口。
- 平级服务只保存 Casdoor 身份映射、服务内资料及自身业务权限。
- 平级服务自己的登录页不验证本地密码,而是由其后端调用 Casdoor。
### 2.3 本期不包含
- 企业微信登录。
- 拒绝用户清理。
- 全局单点退出。
- HXOPS 角色、Agent 权限和功能权限同步到平级服务。
- Casdoor 浏览器 OIDC Cookie SSO 改造。
## 3. 方案结论
采用“双登录通道 + 平级服务专用短时 JWT”:
| 通道 | 使用场景 | 认证方式 |
| --- | --- | --- |
| 平级服务独立登录 | 用户直接访问平级服务 | 平级服务后端使用自己的 Casdoor Application 执行 password grant,并创建本地 Session |
| HXOPS 无感登录 | 用户从 HXOPS 跳转,或在平级服务选择“使用 HXOPS 登录” | HXOPS 为目标服务签发专用短时 JWT,浏览器表单 POST 给平级服务,平级服务验签后创建本地 Session |
该方案不要求 Redis,也不要求平级服务调用 HXOPS 票据兑换接口。
## 4. 目标架构
```mermaid
flowchart LR
U["用户浏览器"]
C["Casdoor<br/>统一用户与密码"]
HFE["HXOPS 前端<br/>登录页 / 平级服务入口"]
HBE["HXOPS 后端<br/>Casdoor 认证 / 专用 JWT 签发"]
SFE["平级服务前端<br/>独立登录页 / 业务页面"]
SBE["平级服务后端<br/>Casdoor 认证 / HXOPS JWT 验证 / 本地 Session"]
K["HXOPS SSO 公钥或 JWKS"]
U --> HFE
HFE --> HBE
HBE -->|"password grant"| C
HBE -->|"签发目标服务专用短时 JWT"| U
U -->|"表单 POST assertion + state"| SBE
SBE -->|"读取公钥并验签"| K
SBE -->|"创建 HttpOnly Session"| SFE
U -->|"直接访问并输入账号密码"| SFE
SFE --> SBE
SBE -->|"独立 client_id/password grant"| C
```
## 5. 信任模型
### 5.1 Casdoor
Casdoor 是产品统一的账号、密码和基础身份事实源:
- HXOPS 使用自己的 Casdoor Application。
- 每个平级服务使用独立的 Casdoor Application。
- 各服务使用不同的 `client_id/client_secret`。
- Casdoor `issuer + subject` 是跨服务稳定身份键。
### 5.2 HXOPS
HXOPS 具有两项职责:
1. 通过 Casdoor 认证 HXOPS 登录页提交的账号密码,并建立 HXOPS API 会话。
2. 在用户已登录 HXOPS 时,为指定平级服务签发短时、受众绑定的登录 JWT。
HXOPS 不向平级服务传递:
- 用户密码。
- Casdoor access token 或 refresh token。
- HXOPS 普通 API JWT。
- HXOPS 角色、功能权限或 Agent 权限。
### 5.3 平级服务
平级服务信任两种身份来源:
- 自身后端直接从 Casdoor 获取并验证的身份。
- HXOPS 使用产品 SSO 私钥签发、且 `aud` 精确绑定本服务的短时 JWT。
两种来源最终都映射到相同的 `(identity_issuer, identity_subject)`。
## 6. JWT 分层
必须区分两种 JWT。
### 6.1 HXOPS API 会话 JWT
仅用于访问 HXOPS 自身 API,不能直接交给平级服务。
示例声明:
```json
{
"iss": "hxops-backend",
"aud": "hxops-frontend",
"sub": "123",
"user_id": 123,
"username": "zhangsan",
"casdoor_iss": "https://login.example.com",
"casdoor_sub": "built-in/zhangsan",
"iat": 1785139200,
"exp": 1785182400
}
```
### 6.2 平级服务专用 SSO JWT
只用于一次登录交接,生命周期建议 30-60 秒。
```json
{
"iss": "https://hxops.example.com",
"aud": "peer-service-a",
"sub": "built-in/zhangsan",
"identity_issuer": "https://login.example.com",
"preferred_username": "zhangsan",
"name": "张三",
"email": "zhangsan@example.com",
"phone_number": "13800000000",
"employee_id": "E1001",
"department": "IT",
"iat": 1785139200,
"nbf": 1785139195,
"exp": 1785139260,
"jti": "random-unique-id"
}
```
约束:
- `aud` 必须是目标平级服务的唯一应用 key。
- `sub` 使用 Casdoor subject,不使用 HXOPS 本地用户 ID。
- `identity_issuer` 必须匹配 HXOPS 可信 Casdoor issuer。
- 不携带 HXOPS 业务权限。
- JWT 不作为平级服务长期会话;验签成功后立即创建平级服务自己的 Session。
## 7. 签名与密钥
### 7.1 推荐算法
产品 SSO JWT 使用非对称签名:
```text
RS256(推荐)或 ES256
```
- HXOPS 保存私钥并负责签发。
- 平级服务只保存公钥或读取 HXOPS JWKS。
- 平级服务没有签发能力,避免任一业务服务伪造其他用户身份。
不建议直接复用 HXOPS API JWT 的 HS256 `SECRET_KEY`。
### 7.2 JWKS
HXOPS 提供公开的验签密钥端点:
```http
GET /.well-known/jwks.json
```
示例:
```json
{
"keys": [{
"kty": "RSA",
"kid": "hxops-product-sso-2026-01",
"use": "sig",
"alg": "RS256",
"n": "...",
"e": "AQAB"
}]
}
```
JWT Header 必须包含当前密钥 `kid`,以支持灰度轮换。
## 8. 登录流程
### 8.1 平级服务自己的登录页
```mermaid
sequenceDiagram
participant U as 浏览器
participant S as 平级服务后端
participant C as Casdoor
U->>S: 提交平级服务登录页账号密码
S->>C: 使用本服务 client_id/client_secret 执行 password grant
C-->>S: access token / ID token / userinfo
S->>S: 验证身份并按 issuer + sub 映射用户
S->>S: 创建服务内 Session,旋转 Session ID
S-->>U: Set-Cookie 并进入业务页面
```
要求:
- 密码只在当前请求中传给 Casdoor,不落库、不写日志。
- 平级服务不调用 HXOPS 的 password-login 接口。
- 平级服务 Casdoor Application 必须独立配置和轮换密钥。
- 用户禁用、密码错误等结果以 Casdoor 为准。
### 8.2 从 HXOPS 无感进入平级服务
```mermaid
sequenceDiagram
participant U as 浏览器
participant H as HXOPS
participant S as 平级服务
U->>H: 已登录 HXOPS
U->>S: 新标签打开 /auth/hxops/start
S->>S: 生成受签名 state,包含安全 return_to 和过期时间
S-->>U: 302 HXOPS /sso/authorize?app=peer-service-a&state=...
U->>H: 携带现有 HXOPS 会话
H->>H: 校验用户、应用白名单与 Casdoor 身份
H-->>U: 返回 post_url、短时 assertion、原 state
U->>S: 表单 POST assertion + state
S->>S: 验证 state、RS256 签名、iss、aud、exp、nbf
S->>S: 映射用户并建立本地 Session
S-->>U: 302 到 return_to
```
浏览器必须使用表单 POST 传递 `assertion`,不能把 JWT 放在 query string 中。
### 8.3 直接访问平级服务后选择“使用 HXOPS 登录”
```mermaid
sequenceDiagram
participant U as 浏览器
participant S as 平级服务
participant H as HXOPS
U->>S: 访问受保护地址,无本地 Session
S-->>U: 展示自己的登录页
U->>S: 点击“使用 HXOPS 登录”
S-->>U: 302 HXOPS /sso/authorize
alt HXOPS 未登录
H-->>U: 转到 HXOPS 现有登录页
U->>H: 输入同一套账号密码
H->>H: 通过 Casdoor 认证
end
H-->>U: POST 专用短时 JWT 回平级服务
S-->>U: 建立 Session 后进入原地址
```
### 8.4 从平级服务返回 HXOPS
平级服务直接链接 HXOPS 白名单业务地址,例如:
```text
https://hxops.example.com/workspace/applications
```
HXOPS 会话有效时直接进入;无会话时由 HXOPS 登录页处理。
## 9. 无 Redis 的 state 设计
为了不依赖 Redis,平级服务可以签发自己的短时 state:
```json
{
"iss": "peer-service-a",
"aud": "hxops-sso",
"return_to": "/orders/42",
"nonce": "random-value",
"iat": 1785139200,
"exp": 1785139500
}
```
平级服务使用仅自身持有的 HMAC 密钥或私钥签名。callback 时必须:
1. 验证 state 签名。
2. 验证 `iss/aud/exp`。
3. 只接受以单个 `/` 开头的服务内相对 `return_to`。
4. 拒绝 `//host/path`、绝对 URL 和超长路径。
无状态 state 不能保证 nonce 只用一次,但在 HTTPS、短 TTL 和严格 callback 校验下可满足同一产品平级服务的风险边界。如果未来要求严格防重放,可在平级服务侧使用 Redis 或数据库保存已用 `nonce/jti`,不影响 HXOPS 主协议。
## 10. HXOPS 接口设计
### 10.1 查询平级服务目录
```http
GET /api/sso/apps
Authorization: Bearer <HXOPS API JWT>
```
```json
{
"items": [{
"key": "peer-service-a",
"display_name": "平级服务 A",
"login_url": "https://service-a.example.com/auth/hxops/start"
}]
}
```
### 10.2 签发专用登录声明
```http
POST /api/sso/apps/peer-service-a/assertions
Authorization: Bearer <HXOPS API JWT>
Content-Type: application/json
{
"state": "<peer-service-signed-state>"
}
```
响应:
```json
{
"post_url": "https://service-a.example.com/auth/hxops/callback",
"assertion": "<RS256-short-lived-JWT>",
"state": "<peer-service-signed-state>",
"expires_in": 60
}
```
HXOPS 必须从服务端应用注册表读取 `post_url/audience`,不得接受浏览器传入 callback URL。
### 10.3 JWKS
```http
GET /.well-known/jwks.json
```
该接口无需登录,只返回公钥,不返回私钥或应用密钥。
## 11. 平级服务接口设计
### 11.1 独立账号密码登录
```http
POST /api/auth/login
Content-Type: application/json
{
"username": "zhangsan",
"password": "user-input"
}
```
平级服务后端调用 Casdoor,成功后创建本地 Session。
### 11.2 发起 HXOPS 登录
```http
GET /auth/hxops/start?return_to=/orders/42
```
生成签名 state,并重定向到 HXOPS `/sso/authorize`。
### 11.3 接收 HXOPS 登录
```http
POST /auth/hxops/callback
Content-Type: application/x-www-form-urlencoded
assertion=<short-lived-jwt>&state=<signed-state>
```
平级服务验证后建立本地 Session,并跳转 state 中的相对 `return_to`。
## 12. 平级服务验证规则
平级服务必须完成全部校验:
1. JWT Header `alg` 固定为 `RS256`,拒绝 `none`、HS256 和算法降级。
2. 根据 `kid` 从可信 JWKS 选择公钥。
3. 签名有效。
4. `iss` 精确等于 HXOPS SSO issuer。
5. `aud` 精确等于本服务 key。
6. `exp` 未过期,`nbf` 已生效。
7. `iat` 与当前时间偏差在允许范围内,建议时钟容差不超过 30 秒。
8. `identity_issuer/sub/jti` 必须存在。
9. state 签名、有效期和 `return_to` 合法。
10. 身份映射成功且本地用户状态允许登录。
验证成功后:
- 以 `(identity_issuer, sub)` upsert 本地用户映射。
- 更新可变资料,如用户名、姓名、邮箱、工号和部门。
- 旋转本地 Session ID。
- 写入 `HttpOnly; Secure; SameSite=Lax` Cookie。
- 不把 assertion 保存到 localStorage、数据库或业务日志。
## 13. 应用注册配置
建议将现有应用注册表调整为:
```json
[
{
"key": "peer-service-a",
"display_name": "平级服务 A",
"login_url": "https://service-a.example.com/auth/hxops/start",
"callback_url": "https://service-a.example.com/auth/hxops/callback",
"audience": "peer-service-a",
"enabled": true
}
]
```
不再需要用于票据兑换的 `client_id/client_secret`。平级服务自己的 Casdoor `client_id/client_secret` 只配置在平级服务后端,与 HXOPS SSO 注册表无关。
HXOPS 建议环境变量:
```dotenv
AUTH_LOGIN_MODE=casdoor
SSO_ENABLED=true
SSO_ASSERTION_TTL_SECONDS=60
SSO_ISSUER=https://hxops.example.com
SSO_SIGNING_ALGORITHM=RS256
SSO_SIGNING_KEY_ID=hxops-product-sso-2026-01
SSO_PRIVATE_KEY_PATH=/run/secrets/hxops_sso_private.pem
SSO_ADDITIONAL_PUBLIC_KEYS_JSON=[{"kid":"hxops-product-sso-2025-12","public_key_path":"/run/secrets/hxops_sso_old_public.pem"}]
SSO_APPS_JSON=[...]
```
平级服务建议环境变量:
```dotenv
CASDOOR_BASE_URL=https://login.example.com
CASDOOR_CLIENT_ID=peer-service-a-client
CASDOOR_CLIENT_SECRET=<secret-manager-value>
HXOPS_SSO_ISSUER=https://hxops.example.com
HXOPS_SSO_AUDIENCE=peer-service-a
HXOPS_SSO_JWKS_URL=https://hxops.example.com/.well-known/jwks.json
HXOPS_SSO_STATE_SECRET=<peer-service-owned-secret>
```
## 14. 权限与状态
认证只解决“用户是谁”,不直接解决“用户能做什么”。
- HXOPS 权限继续由 HXOPS 管理。
- 平级服务业务权限由平级服务管理。
- 如存在产品级基础角色,应另行定义最小、稳定的角色契约。
- 不将完整权限列表写入 SSO JWT,避免权限变更后旧 JWT 仍携带过期权限。
用户在 HXOPS/Casdoor 被禁用后,平级服务已有 Session 不会自动消失。平级服务应结合风险选择:
- 较短 Session 有效期。
- 定期查询用户状态。
- 接收 HXOPS 用户状态变更 webhook。
- 高风险操作前重新验证状态。
## 15. 退出策略
### 15.1 退出当前平级服务
只清除平级服务自己的 Session,不影响 HXOPS 和其他服务。
### 15.2 退出 HXOPS
只清除 HXOPS 会话。已建立的平级服务 Session 默认继续有效。
### 15.3 全局退出
本期不实现。未来可通过统一会话中心、后端注销通知或 Casdoor 标准 logout 能力扩展。
## 16. 安全要求
- 所有生产入口使用 HTTPS。
- 密码只提交给当前服务后端,再由后端发送给 Casdoor;禁止浏览器直传 `client_secret`。
- 专用 SSO JWT 仅通过表单 POST 传递,不放 URL。
- SSO JWT 有效期 30-60 秒,严格绑定 audience。
- HXOPS 私钥使用 Secret Manager 或只读挂载,不提交仓库。
- JWKS 支持双 key 轮换期。
- callback 和 login URL 必须来自 HXOPS 服务端白名单。
- `return_to` 只允许平级服务内部相对路径。
- 日志不得记录密码、完整 JWT、Casdoor token、refresh token 或私钥。
- 平级服务创建 Session 后必须旋转 Session ID。
## 17. 与一次性票据方案对比
| 项目 | 专用短时 JWT | 一次性票据兑换 |
| --- | --- | --- |
| HXOPS Redis | 不需要 | 需要 |
| 平级服务回调时调用 HXOPS | 不需要 | 需要 |
| 多实例 | 天然支持 | 依赖共享 Redis |
| 严格一次性 | 默认不保证 | 原生保证 |
| 验证方式 | HXOPS 公钥离线验签 | 调 HXOPS exchange 接口 |
| 密钥 | HXOPS 私钥、服务只持公钥 | 每服务 client secret |
| 适用场景 | 同产品、统一信任边界的平级服务 | 外部或更高安全边界的第三方系统 |
本场景采用专用短时 JWT。若未来接入真正外部系统,可重新评估 OIDC 或一次性票据方案。
## 18. 实施范围
### 18.1 HXOPS 改造(已完成)
1. 已保留 Casdoor password-login 和 HXOPS API 会话 JWT。
2. 已将应用注册表从票据客户端配置调整为 `audience/callback_url`。
3. 已使用 `/assertions` 签发 RS256 短时 JWT,并移除 `/tickets`。
4. 已移除 `/api/sso/exchange` 和 Redis 票据存储依赖。
5. 已新增 JWKS 端点和 `kid`,支持当前签名公钥与旧验证公钥并行发布完成平滑轮换。
6. 前端授权页已将 `assertion/state` 通过表单 POST 给平级服务。
7. 已保留登录续跳和多页面平级服务入口。
### 18.2 平级服务改造
1. 创建独立 Casdoor Application。
2. 实现自己的账号密码登录页和 Casdoor password grant 后端。
3. 实现 `/auth/hxops/start` 与签名 state。
4. 实现 `/auth/hxops/callback` 和 HXOPS JWT 验证。
5. 按 `issuer + sub` 建立用户映射。
6. 创建服务内安全 Session。
7. 移除用户和密码维护入口。
### 18.3 认证代码复用边界(HXOPS 已完成第一阶段重构)
后端认证代码按“可直接复制”和“HXOPS 专属”拆分,当前不发布依赖包:
```text
backend/app/services/auth/
common/ # 纯身份对象与 issuer + subject 稳定键
casdoor/ # Casdoor 配置、OAuth/OIDC HTTP、claims 解析、错误映射
hxops/ # HXOPS 用户映射、本地 JWT、登录编排、用户同步
casdoor_service.py # 历史调用兼容门面,不承载新的核心实现
```
平级服务实现自己的登录页时,可以复制 `common/` 与 `casdoor/`,然后按自身框架替换配置适配器、用户映射和 Session 创建。不得复制 HXOPS 的 `User` 模型、角色权限或本地 API JWT 签发逻辑。
本阶段结构重构保持以下外部契约不变:
- HXOPS 登录协议、API 路径和响应字段不变。
- Casdoor password/code/refresh grant 行为不变。
- HXOPS API JWT claims、签名算法和有效期语义不变。
- SSO assertion/JWKS 协议不变。
- 数据库表结构和用户映射规则不变。
Casdoor discovery 文档由配置对应的进程内客户端缓存 10 分钟;配置变化时自动创建新客户端。用户创建、管理员改密和 IdP 缺失用户补建集中在 `hxops/casdoor_user_sync.py`,旧入口继续通过兼容门面委托,以便分阶段迁移调用方。
`AUTH_JWT_ISSUER` 必须填写 `CASDOOR_BASE_URL/.well-known/openid-configuration` 返回的 `issuer`,不能填写 HXOPS 前端/后端地址,也不能简单使用 Casdoor 内网访问地址。HXOPS 会对 ID token/userinfo 中的 `iss` 做严格匹配;配置不一致时返回 `AUTH.CASDOOR_IDENTITY_INVALID`。
## 19. 测试方案
### 19.1 HXOPS 登录
- 正确 Casdoor账号密码登录成功。
- 错误密码、禁用用户和未同步用户正确拒绝。
- 登录成功后 HXOPS API 会话稳定,不因平级服务目录加载失败而退出。
- refresh 后仍返回有效 HXOPS API JWT,并保留 Casdoor身份引用。
### 19.2 专用 JWT 签发
- 未登录、guest、禁用用户不能签发。
- 非 Casdoor身份不能签发。
- 未注册或禁用服务不能签发。
- `iss/aud/sub/identity_issuer/iat/nbf/exp/jti` 正确。
- 不包含 HXOPS权限、Casdoor token和密码。
- 每次签发的 `jti` 不同。
- TTL 超出配置边界时安全拒绝或收敛到允许范围。
### 19.3 平级服务验签
- 正确 JWT 成功建立 Session。
- 错误签名、错误 `kid`、错误算法、错误 issuer/audience 拒绝。
- 过期、尚未生效、缺少必要 claim 的 JWT 拒绝。
- 非法或过期 state、外部 `return_to` 拒绝。
- 两种登录入口映射到同一个本地用户。
### 19.4 端到端
- HXOPS 登录后点击平级服务,无密码进入。
- 新标签与当前标签登录状态均正确。
- 直接访问平级服务时显示自己的登录页,并能使用同一账号密码登录。
- 平级服务“使用 HXOPS 登录”在 HXOPS 已登录/未登录两种情况下都正确返回原页面。
- 平级服务返回 HXOPS 链接正常。
- HXOPS 或平级服务单独退出不会错误清除另一服务 Session。
## 20. 验收标准
1. HXOPS 和平级服务使用 Casdoor 同一套用户和密码。
2. 用户从 HXOPS 点击平级服务时不出现第二次账号密码输入。
3. 用户直接访问平级服务时可以使用其自己的登录页登录。
4. 平级服务不保存独立密码,不提供用户和密码维护入口。
5. 无感登录不依赖 Redis,也不调用 HXOPS 票据兑换接口。
6. HXOPS 不把普通 API JWT、Casdoor token、密码或业务权限交给平级服务。
7. 平级服务只接受面向自身 audience、有效期不超过 60 秒的 HXOPS 专用 JWT。
8. assertion 不出现在 URL、浏览器历史和常规访问日志中。
9. 两种登录方式均按 Casdoor `issuer + subject` 映射到同一个用户。
10. 错误签名、错误 audience、过期 JWT、非法 state 和外部跳转均被拒绝。
## 21. 上线步骤
1. 为每个平级服务创建独立 Casdoor Application。
2. 生成 HXOPS 产品 SSO RSA 密钥并安全配置私钥。
3. 发布 HXOPS JWKS 和 assertion 签发接口。
4. 平级服务实现 Casdoor登录、HXOPS验签和本地 Session。
5. 在测试环境完成第 19、20 节。
6. 灰度开放一个平级服务入口。
7. 确认稳定后移除旧票据接口、Redis票据配置和旧文档。
@@ -0,0 +1,7 @@
# 已废弃:外部第三方一次性票据方案
原方案将目标系统视为外部第三方,并使用 Redis 一次性票据完成登录兑换。
经需求重新确认,目标系统属于 HXOPS 同一产品下的平级服务,可以保留自己的 Casdoor 登录页;从 HXOPS 进入时使用面向目标服务的专用短时 JWT 实现无感登录,不再要求 Redis。
新的权威方案见 [HXOPS 产品内平级服务统一认证技术方案](hxops-peer-service-sso.md)。
+21
View File
@@ -560,3 +560,24 @@
- [x] 抬头区域排除且不展示、正文限定比对、签章排除
- [x] 附件仅提示页数变化且不计入差异/风险统计
- [x] 锚点或分页失败时全文比对安全回退提示
# HXOPS 与产品内平级服务统一认证(2026-07-27)
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| HXOPS Casdoor 表单登录 | 已实现 | 用户只在 HXOPS 登录页输入用户名/密码,后端调用 Casdoor password-login,不跳转 Casdoor 页面。 |
| HXOPS API 会话 JWT | 已实现 | Casdoor 校验成功后由 HXOPS 签发本站 API JWT,并保留 Casdoor 稳定身份声明。 |
| 认证公共结构第一阶段重构 | 已实现 | 已拆分 `common/casdoor/hxops` 三层;平级服务可直接复制无业务模型依赖的 `common` 与 `casdoor`,旧入口由兼容门面保持不变。 |
| 平级服务注册表与入口 | 已实现 | 服务端应用目录使用 `audience/callback_url`,工作台、Chat、Admin 和移动端复用统一入口组件。 |
| HXOPS 登录续跳 | 已实现 | 未登录授权请求保存到 sessionStorage,登录成功后自动恢复 assertion 签发流程。 |
| RS256 专用短时 JWT 签发 | 已实现 | `/api/sso/apps/{app_key}/assertions` 按目标服务绑定 `aud`,配置有效期限制为 10-60 秒。 |
| HXOPS JWKS 发布与轮换 | 已实现 | `/.well-known/jwks.json` 发布当前 RSA 公钥,并可在换钥窗口继续发布旧验证公钥。 |
| 平级服务独立 Casdoor 登录 | 待平级服务实现 | 平级服务保留自己的登录页,后端使用独立 Casdoor Application 校验同一套账号密码并创建本地 Session。 |
| 平级服务 HXOPS 无感登录 | 待平级服务实现 | 验证 HXOPS assertion 和签名 state,以 `(issuer, subject)` 映射用户并创建本地 Session。 |
| Redis 一次性票据实现 | 已移除 | `/tickets`、`/api/sso/exchange`、客户端密钥认证和 Redis 票据存储代码均已删除。 |
| 端到端联调与验收 | 待进行 | 覆盖 HXOPS 跳转、平级服务独立登录、“使用 HXOPS 登录”、返回 HXOPS、退出和异常验签。 |
| 跨服务业务权限同步 | 未纳入本期 | HXOPS 角色、功能权限和 Agent 权限不下发,平级服务独立授权。 |
详细目标架构、接口契约、测试矩阵与验收标准见 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md)。
---
+15
View File
@@ -1135,3 +1135,18 @@ Dify
- 两份上传文件均识别成功后,仅将 `body` 传入既有 `analyze_compare`;`metadata/signature/attachments` 分别进入字段对照、排除区和页数汇总。
- `summary_json` 扩展 `comparison_scope`、`metadata_comparison`、`attachment_comparison`;`clauses_json` 与 Chat 发起接口保持兼容。
- 区域处理为 fail-safe:任何一侧正文锚点或可靠分页缺失时,使用旧全文比对结果并记录回退原因。
# HXOPS 产品内平级服务统一认证技术补充(2026-07-27)
- Casdoor 是统一密码校验和身份来源。HXOPS 与每个平级服务使用各自的 Casdoor Application,均以稳定的 Casdoor `(issuer, subject)` 建立用户映射。
- HXOPS 前端保留现有登录表单;`AUTH_LOGIN_MODE=casdoor` 时后端调用 Casdoor password grant,成功后由 HXOPS 签发仅供本站 API 使用的会话 JWT。
- 平级服务可保留独立登录页,由其后端直接调用 Casdoor password grant 并创建自己的 HttpOnly Session;平级服务不调用 HXOPS 密码登录接口,也不保存独立密码。
- 从 HXOPS 无感进入平级服务时,HXOPS 通过 `POST /api/sso/apps/{app_key}/assertions` 签发 RS256 专用短时 JWT。JWT 必须绑定目标 `aud`,有效期不超过 60 秒,并通过表单 POST 到白名单 callback。
- 平级服务根据 JWT `kid` 从 HXOPS `/.well-known/jwks.json` 获取公钥,严格校验算法、签名、`iss/aud/sub/iat/nbf/exp`,验签成功后旋转 Session ID 并建立自己的会话。
- HXOPS API JWT 与平级服务 SSO JWT 是不同凭据;普通 API JWT、Casdoor token、密码、角色和 Agent 权限不得传给平级服务。
- `state` 由平级服务签名并限制短时有效,内含随机 nonce 和经过校验的相对 `return_to`;目标方案保持无状态,不要求 HXOPS 或平级服务使用 Redis。若未来要求严格一次性防重放,可由平级服务保存已使用的 `nonce/jti`。
- HXOPS 前端保留登录续跳和统一平级服务入口;平级服务可提供“使用 HXOPS 登录”及返回 HXOPS 的普通 HTTPS 链接。
- HXOPS 已移除 `/tickets`、`/api/sso/exchange` 和 Redis 票据存储,统一使用 assertion/JWKS 协议。平级服务独立登录、验签和本地 Session 仍在对应代码库实现。完整接口、密钥轮换、安全约束、测试与验收见 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md)。
- 认证代码第一阶段结构重构已落地:`services/auth/common` 定义无框架稳定身份,`services/auth/casdoor` 封装可复制的配置、OAuth/OIDC 客户端、claims 与错误映射,`services/auth/hxops` 承载用户映射、本地 JWT、登录编排及用户同步;`casdoor_service.py` 仅保留旧调用兼容门面。本阶段不改变协议、接口路径、响应格式、JWT 语义或数据库结构。
---
+4 -1
View File
@@ -62,7 +62,10 @@ watch(themePreference, (newTheme) => {
updateThemePreference(newTheme);
});
const onUnauthorized = () => {
const onUnauthorized = (event: Event) => {
const url = String((event as CustomEvent<{ url?: string }>).detail?.url || '');
// 外部应用目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return;
showMessageDialog('error', '认证已过期或无效,请重新登录');
logoutAuth();
};
@@ -5,9 +5,13 @@
import type { RouteRecordRaw } from 'vue-router';
import LoginView from '@/features/auth/views/LoginView.vue';
import ResetPasswordView from '@/features/auth/views/ResetPasswordView.vue';
import SsoAuthorizeView from '@/features/sso/views/SsoAuthorizeView.vue';
import SsoLaunchView from '@/features/sso/views/SsoLaunchView.vue';
export const authRoutes: RouteRecordRaw[] = [
{ path: '/login', name: 'Login', component: LoginView },
{ path: '/casdoor-callback', name: 'CasdoorCallback', component: LoginView },
{ path: '/reset-password', name: 'ResetPassword', component: ResetPasswordView },
{ path: '/sso/authorize', name: 'SsoAuthorize', component: SsoAuthorizeView },
{ path: '/sso/launch', name: 'SsoLaunch', component: SsoLaunchView },
];
+1 -1
View File
@@ -4,7 +4,7 @@ export const config = {
// Login mode switch:
// - 'casdoor': submit username/password to backend Casdoor password-login API.
// - 'password': submit to legacy local /api/user/login.
loginMode: 'password',
loginMode: 'casdoor',
casdoor: {
enabled: true,
authorizeApi: '/api/user/casdoor/authorize-url',
@@ -12,6 +12,7 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
import loginBg from '@/assets/login-bg.png';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import { useWorkspaceLocale } from '@/features/workspace/composables/useWorkspaceLocale';
import { continuationLocation, readSsoContinuation } from '@/features/sso';
import { useLoginAuth } from './useLoginAuth';
import { useLoginLanding } from './useLoginLanding';
@@ -28,11 +29,21 @@ export function useLogin() {
const completePasswordLogin = async () => {
authStore.syncFromStorage();
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
return;
}
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
const completeOAuthLogin = async () => {
authStore.syncFromStorage();
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
return;
}
await router.replace('/workspace/applications');
};
@@ -58,7 +69,8 @@ export function useLogin() {
authStore.syncFromStorage();
if (authStore.isLoggedIn) {
await router.replace('/workspace/applications');
const continuation = readSsoContinuation();
await router.replace(continuation ? continuationLocation(continuation) : '/workspace/applications');
return;
}
@@ -6,6 +6,7 @@
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { BookOpen, History, LayoutGrid } from 'lucide-vue-next';
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
import { ExternalSystemLinks } from '@/features/sso';
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
export interface ChatMobileHeaderAgent extends AgentWithCategory {}
@@ -76,6 +77,7 @@ onBeforeUnmount(() => {
</button>
</div>
<div class="flex items-center gap-1">
<ExternalSystemLinks compact :show-label="false" />
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
@@ -1,7 +1,7 @@
/**
* features/chat/components/ChatSidebar.vue
* 用途:桌面端聊天侧栏,承载 Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
* 依赖:lucide-vue-next、LocaleToggleButton、AgentCategoryList、chat.types。
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈、进入管理控制台等操作回传给页面。
* 管理员通过底部右侧工具图标进入管理控制台;用户下拉菜单仅保留退出登录。
*/
@@ -25,6 +25,7 @@ import {
X,
} from 'lucide-vue-next';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import { ExternalSystemLinks } from '@/features/sso';
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
import { isHrFocusedAgent, type AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
@@ -128,6 +129,7 @@ const userInitial = (fallback: string) => {
</button>
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-muted">
<ExternalSystemLinks compact :show-label="false" />
<button type="button" class="transition-colors hover:text-secondary"><Sparkles class="h-5 w-5" /></button>
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
{{ userInitial('I') }}
@@ -301,6 +303,7 @@ const userInitial = (fallback: string) => {
</div>
<div class="flex gap-3">
<ExternalSystemLinks compact :show-label="false" />
<button
type="button"
class="transition-colors hover:text-secondary"
+39
View File
@@ -0,0 +1,39 @@
/**
* features/sso/api/sso.api.ts
* 用途:访问 HXOPS 平级服务目录与短时登录 assertion 签发接口。
* 依赖:shared/api/client。
* 逻辑:导航组件读取安全服务元数据;授权页按 app key 请求受众绑定 JWT 和服务端登记的回调地址。
*/
import { requestJson } from '@/shared/api/client';
export interface SsoApplication {
key: string;
display_name: string;
login_url: string;
}
export interface SsoAssertionResponse {
post_url: string;
assertion: string;
state: string;
expires_in: number;
}
/** 获取当前用户可见的已启用产品内平级服务。 */
export async function listSsoApplications(): Promise<SsoApplication[]> {
const data = await requestJson<{ items?: SsoApplication[] }>('/api/sso/apps');
return Array.isArray(data?.items) ? data.items : [];
}
/**
* 为目标平级服务签发受众绑定的短时登录 assertion。
* @param appKey - 服务端配置的应用 key,不能传 callback URL。
* @param state - 平级服务签名的短时 state,HXOPS 仅原样返回。
*/
export function createSsoAssertion(appKey: string, state: string): Promise<SsoAssertionResponse> {
return requestJson<SsoAssertionResponse>(`/api/sso/apps/${encodeURIComponent(appKey)}/assertions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state }),
});
}
@@ -0,0 +1,54 @@
<!--
features/sso/components/ExternalSystemLinks.vue
用途:在 HXOPS 已登录页面展示已配置产品内平级服务入口。
依赖:SSO 应用目录 API、lucide-vue-next。
逻辑:点击后先打开 HXOPS 同源 launch 页以继承当前登录态,再由 launch 页跳平级服务生成签名 state。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ExternalLink } from 'lucide-vue-next';
import { listSsoApplications, type SsoApplication } from '../api/sso.api';
withDefaults(defineProps<{
compact?: boolean;
showLabel?: boolean;
}>(), {
compact: false,
showLabel: true,
});
const applications = ref<SsoApplication[]>([]);
/** 加载已启用应用;目录不可用时隐藏入口,不阻断 HXOPS 主业务。 */
async function loadApplications(): Promise<void> {
try {
applications.value = await listSsoApplications();
} catch (error) {
console.warn('[sso] failed to load peer services', error);
}
}
/** 在新标签先打开同源中转页,确保非 remember 登录态也可继承到新标签。 */
function openApplication(application: SsoApplication): void {
window.open(`/sso/launch?app=${encodeURIComponent(application.key)}`, '_blank');
}
onMounted(() => {
void loadApplications();
});
</script>
<template>
<template v-for="application in applications" :key="application.key">
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:class="compact ? 'h-9 w-9' : 'min-h-9 px-3 py-2 text-sm'"
:title="application.display_name"
@click="openApplication(application)"
>
<ExternalLink class="h-4 w-4 shrink-0" />
<span v-if="showLabel && !compact" class="truncate">{{ application.display_name }}</span>
</button>
</template>
</template>
+11
View File
@@ -0,0 +1,11 @@
/**
* features/sso/index.ts
* 用途:统一导出 SSO 复用组件与续跳能力。
* 依赖:features/sso 子模块。
* 逻辑:页面通过本入口复用平级服务导航,登录模块复用 continuation。
*/
export { default as ExternalSystemLinks } from './components/ExternalSystemLinks.vue';
export {
continuationLocation,
readSsoContinuation,
} from './utils/continuation';
@@ -0,0 +1,72 @@
/**
* features/sso/utils/continuation.ts
* 用途:在平级服务跳转到 HXOPS 登录页期间保存并恢复 SSO 请求。
* 依赖:浏览器 sessionStorage、Vue Router 查询参数类型。
* 逻辑:只保存 app key 和签名 state,不接收或持久化 callback URL、JWT 或用户资料。
*/
import type { LocationQuery } from 'vue-router';
export interface SsoContinuation {
app: string;
state: string;
createdAt: number;
}
const STORAGE_KEY = 'hxops_sso_continuation';
const MAX_AGE_MS = 10 * 60 * 1000;
const APP_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{1,63}$/;
/** 从授权路由查询参数构造安全的续跳请求。 */
export function parseSsoContinuation(query: LocationQuery): SsoContinuation | null {
const app = typeof query.app === 'string' ? query.app.trim().toLowerCase() : '';
const state = typeof query.state === 'string' ? query.state.trim() : '';
if (!APP_KEY_PATTERN.test(app) || !state || state.length > 4096) return null;
return { app, state, createdAt: Date.now() };
}
/** 保存未登录用户的 SSO 请求,登录成功后在同一标签页恢复。 */
export function saveSsoContinuation(continuation: SsoContinuation): void {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(continuation));
}
/** 读取仍在有效期内的 SSO 请求;坏数据或超时数据会立即清理。 */
export function readSsoContinuation(): SsoContinuation | null {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const data = JSON.parse(raw) as Partial<SsoContinuation>;
if (
!APP_KEY_PATTERN.test(String(data.app || ''))
|| !String(data.state || '')
|| String(data.state || '').length > 4096
|| Date.now() - Number(data.createdAt || 0) > MAX_AGE_MS
) {
clearSsoContinuation();
return null;
}
return {
app: String(data.app),
state: String(data.state),
createdAt: Number(data.createdAt),
};
} catch {
clearSsoContinuation();
return null;
}
}
/** 清理已完成或无效的登录续跳请求。 */
export function clearSsoContinuation(): void {
sessionStorage.removeItem(STORAGE_KEY);
}
/** 生成只包含服务端应用 key 的 HXOPS 授权路由。 */
export function continuationLocation(continuation: SsoContinuation) {
return {
path: '/sso/authorize',
query: {
app: continuation.app,
state: continuation.state,
},
};
}
@@ -0,0 +1,27 @@
/**
* features/sso/utils/postForm.ts
* 用途:用浏览器表单 POST 将短时 SSO assertion 交给已登记的平级服务回调。
* 依赖:DOM API。
* 逻辑:assertion 只进入请求体,不拼接 URL;提交后浏览器离开 HXOPS 授权页。
*/
/**
* POST assertion 和 state 到后端返回的已登记回调地址。
* @param action - HXOPS 服务端从应用注册表返回的绝对 HTTPS callback URL。
* @param fields - 仅包含 assertion 与平级服务原始 state。
*/
export function submitSsoForm(action: string, fields: Record<string, string>): void {
const form = document.createElement('form');
form.method = 'POST';
form.action = action;
form.style.display = 'none';
for (const [name, value] of Object.entries(fields)) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
@@ -0,0 +1,73 @@
<!--
features/sso/views/SsoAuthorizeView.vue
用途:承接平级服务登录请求;未登录时转 HXOPS 登录页,已登录时签发 assertion 并 POST 回平级服务。
依赖:auth store、SSO API、continuation 与 postForm 工具。
逻辑:平级服务只提供 app/state;callback 与 JWT audience 始终由 HXOPS 服务端注册表决定。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { createSsoAssertion } from '../api/sso.api';
import {
clearSsoContinuation,
parseSsoContinuation,
saveSsoContinuation,
} from '../utils/continuation';
import { submitSsoForm } from '../utils/postForm';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const errorMessage = ref('');
/** 校验授权请求,并按当前登录状态执行保存续跳或签发短时 assertion。 */
async function authorize(): Promise<void> {
const continuation = parseSsoContinuation(route.query);
if (!continuation) {
errorMessage.value = t('common.sso.invalidRequest');
return;
}
authStore.syncFromStorage();
if (!authStore.isLoggedIn) {
saveSsoContinuation(continuation);
await router.replace('/login');
return;
}
try {
const result = await createSsoAssertion(continuation.app, continuation.state);
clearSsoContinuation();
submitSsoForm(result.post_url, { assertion: result.assertion, state: result.state });
} catch (error) {
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
}
}
onMounted(() => {
void authorize();
});
</script>
<template>
<main class="page-shell flex min-h-screen items-center justify-center px-6">
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
<template v-if="!errorMessage">
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
<p class="mt-2 text-sm text-muted">{{ t('common.sso.authorizingHint') }}</p>
</template>
<template v-else>
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
</button>
</template>
</section>
</main>
</template>
@@ -0,0 +1,63 @@
<!--
features/sso/views/SsoLaunchView.vue
用途:在新标签先继承 HXOPS sessionStorage,再安全跳转到平级服务登录起点。
依赖:SSO 应用目录 API、Vue Router。
逻辑:页面只接收 app key,加载后立即切断 opener,目标 URL 由 HXOPS 服务端注册表提供。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { listSsoApplications } from '../api/sso.api';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const errorMessage = ref('');
// 新标签已完成同源 sessionStorage 克隆,跳跨域前切断 opener 防止反向标签劫持。
window.opener = null;
/** 按服务端应用目录解析 app key,并跳转到平级服务登录起点。 */
async function launch(): Promise<void> {
const appKey = typeof route.query.app === 'string' ? route.query.app.trim().toLowerCase() : '';
if (!appKey) {
errorMessage.value = t('common.sso.invalidRequest');
return;
}
try {
const applications = await listSsoApplications();
const application = applications.find((item) => item.key === appKey);
if (!application) {
errorMessage.value = t('errors.codes.AUTH_SSO_APP_NOT_FOUND');
return;
}
window.location.replace(application.login_url);
} catch (error) {
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
}
}
onMounted(() => {
void launch();
});
</script>
<template>
<main class="page-shell flex min-h-screen items-center justify-center px-6">
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
<template v-if="!errorMessage">
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
</template>
<template v-else>
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
</button>
</template>
</section>
</main>
</template>
@@ -1,7 +1,7 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、返回聊天与退出登录。
* 工作台左侧导航:子路由链接、第三方系统、返回聊天与退出登录。
*/
import { inject } from 'vue';
import { useRoute } from 'vue-router';
@@ -10,6 +10,7 @@ import {
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import { ExternalSystemLinks } from '@/features/sso';
defineProps<{
collapsed?: boolean;
@@ -106,6 +107,7 @@ function isActive(match: readonly string[]) {
<div class="border-t border-subtle pt-4">
<div class="space-y-2">
<ExternalSystemLinks :compact="Boolean(collapsed)" :show-label="!collapsed" />
<button
type="button"
@click="ws.navigateToGeneralChat"
@@ -10,6 +10,7 @@ import { useWorkspace } from '../composables/useWorkspace';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import WorkspaceSidebar from '../components/WorkspaceSidebar.vue';
import WorkspaceModals from '../components/WorkspaceModals.vue';
import { ExternalSystemLinks } from '@/features/sso';
const ws = useWorkspace();
provide(WORKSPACE_KEY, ws);
@@ -40,6 +41,7 @@ const mobileTabs = [
</button>
<span class="text-sm font-semibold text-primary">{{ ws.mobileTabTitle }}</span>
</div>
<ExternalSystemLinks compact :show-label="false" />
</header>
<div
+7
View File
@@ -8,6 +8,13 @@
"refresh": "Refresh",
"yes": "Yes",
"no": "No",
"sso": {
"authorizing": "Opening the external system",
"authorizingHint": "Completing secure single sign-on. Please wait.",
"failed": "Single sign-on failed",
"invalidRequest": "The external login request is invalid or expired. Start again from the target system.",
"backToHxops": "Back to HXOPS"
},
"deleteDialog": {
"defaultTitle": "Are you sure you want to delete?",
"defaultMessage": "When clicked the OK button, this dialog will be closed after 1 second",
+5
View File
@@ -6,6 +6,11 @@
"AUTH_INCORRECT_CURRENT_PASSWORD": "Incorrect current password",
"AUTH_USER_NOT_FOUND": "User not found",
"AUTH_ACCOUNT_DISABLED": "Account is disabled",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor did not return a stable user identity. Check the OIDC configuration.",
"AUTH_SSO_CONFIG_ERROR": "The SSO application configuration is invalid. Contact an administrator.",
"AUTH_SSO_APP_NOT_FOUND": "The target system is not configured or is disabled.",
"AUTH_SSO_IDENTITY_UNSUPPORTED": "The current session is not backed by Casdoor. Log in again and retry.",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
"AUTH_FORBIDDEN": "You do not have permission to perform this action.",
"RESOURCE_NOT_FOUND": "The requested resource was not found.",
"RESOURCE_CONFLICT": "Request conflict. Please refresh and try again.",
+7
View File
@@ -8,6 +8,13 @@
"refresh": "รีเฟรช",
"yes": "ใช่",
"no": "ไม่",
"sso": {
"authorizing": "กำลังเปิดระบบภายนอก",
"authorizingHint": "กำลังดำเนินการเข้าสู่ระบบแบบครั้งเดียวอย่างปลอดภัย โปรดรอสักครู่",
"failed": "การเข้าสู่ระบบแบบครั้งเดียวล้มเหลว",
"invalidRequest": "คำขอเข้าสู่ระบบภายนอกไม่ถูกต้องหรือหมดอายุ โปรดเริ่มใหม่จากระบบเป้าหมาย",
"backToHxops": "กลับไป HXOPS"
},
"deleteDialog": {
"defaultTitle": "คุณแน่ใจหรือไม่ว่าต้องการลบ?",
"defaultMessage": "เมื่อกดปุ่มตกลง กล่องโต้ตอบนี้จะปิดหลังจาก 1 วินาที",
+5
View File
@@ -6,6 +6,11 @@
"AUTH_INCORRECT_CURRENT_PASSWORD": "รหัสผ่านปัจจุบันไม่ถูกต้อง",
"AUTH_USER_NOT_FOUND": "ไม่พบผู้ใช้",
"AUTH_ACCOUNT_DISABLED": "บัญชีถูกปิดใช้งาน",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor ไม่ได้ส่งคืนข้อมูลระบุตัวผู้ใช้ที่คงที่ โปรดตรวจสอบการตั้งค่า OIDC",
"AUTH_SSO_CONFIG_ERROR": "การตั้งค่าแอป SSO ไม่ถูกต้อง โปรดติดต่อผู้ดูแลระบบ",
"AUTH_SSO_APP_NOT_FOUND": "ยังไม่ได้ตั้งค่าระบบเป้าหมายหรือระบบถูกปิดใช้งาน",
"AUTH_SSO_IDENTITY_UNSUPPORTED": "เซสชันปัจจุบันไม่ได้ยืนยันผ่าน Casdoor โปรดเข้าสู่ระบบใหม่",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
"RESOURCE_NOT_FOUND": "ไม่พบทรัพยากรที่ร้องขอ",
"RESOURCE_CONFLICT": "คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่",
+7
View File
@@ -8,6 +8,13 @@
"refresh": "刷新",
"yes": "是",
"no": "否",
"sso": {
"authorizing": "正在进入第三方系统",
"authorizingHint": "正在安全地完成统一登录,请稍候。",
"failed": "统一登录失败",
"invalidRequest": "第三方登录请求无效或已过期,请从目标系统重新发起。",
"backToHxops": "返回 HXOPS"
},
"deleteDialog": {
"defaultTitle": "您确定要删除吗?",
"defaultMessage": "点击“确定”按钮后,该对话框将在 1 秒后关闭",
+5
View File
@@ -6,6 +6,11 @@
"AUTH_INCORRECT_CURRENT_PASSWORD": "当前密码不正确",
"AUTH_USER_NOT_FOUND": "用户不存在",
"AUTH_ACCOUNT_DISABLED": "账号已禁用",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回稳定用户身份,请联系管理员检查 OIDC 配置。",
"AUTH_SSO_CONFIG_ERROR": "统一登录应用配置无效,请联系管理员。",
"AUTH_SSO_APP_NOT_FOUND": "目标系统未配置或已停用。",
"AUTH_SSO_IDENTITY_UNSUPPORTED": "当前登录不是 Casdoor 身份,请重新登录后重试。",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
"AUTH_FORBIDDEN": "你没有权限执行该操作。",
"RESOURCE_NOT_FOUND": "请求的资源不存在。",
"RESOURCE_CONFLICT": "请求冲突,请刷新后重试。",
+7
View File
@@ -8,6 +8,13 @@
"refresh": "刷新",
"yes": "是",
"no": "否",
"sso": {
"authorizing": "正在進入第三方系統",
"authorizingHint": "正在安全地完成統一登入,請稍候。",
"failed": "統一登入失敗",
"invalidRequest": "第三方登入請求無效或已過期,請從目標系統重新發起。",
"backToHxops": "返回 HXOPS"
},
"deleteDialog": {
"defaultTitle": "您確定要刪除嗎?",
"defaultMessage": "點擊「確定」按鈕後,此對話框將在 1 秒後關閉",
+5
View File
@@ -6,6 +6,11 @@
"AUTH_INCORRECT_CURRENT_PASSWORD": "當前密碼不正確",
"AUTH_USER_NOT_FOUND": "用戶不存在",
"AUTH_ACCOUNT_DISABLED": "帳號已禁用",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回穩定用戶身份,請聯絡管理員檢查 OIDC 設定。",
"AUTH_SSO_CONFIG_ERROR": "統一登入應用設定無效,請聯絡管理員。",
"AUTH_SSO_APP_NOT_FOUND": "目標系統未設定或已停用。",
"AUTH_SSO_IDENTITY_UNSUPPORTED": "目前登入不是 Casdoor 身份,請重新登入後再試。",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
"AUTH_FORBIDDEN": "你沒有權限執行此操作。",
"RESOURCE_NOT_FOUND": "請求的資源不存在。",
"RESOURCE_CONFLICT": "請求衝突,請刷新後重試。",
+2 -1
View File
@@ -26,6 +26,7 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Res
url.includes('/api/user/login') ||
url.includes('/api/user/casdoor/password-login') ||
url.includes('/api/user/casdoor/login');
const isOptionalSsoCatalogApi = /\/api\/sso\/apps(?:\?|$)/.test(url);
if (res.status === 401 && isApi && !isRefreshApi) {
const refreshed = await refreshAccessToken();
if (refreshed) {
@@ -35,7 +36,7 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Res
res = await runFetch(reqInit);
}
}
if (res.status === 401 && isApi && !isLoginApi) {
if (res.status === 401 && isApi && !isLoginApi && !isOptionalSsoCatalogApi) {
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
}
} catch {
+1 -1
View File
@@ -3,7 +3,7 @@
* 全局路由 path 常量与公开路径判定。
*/
/** 无需登录即可访问的路由 path */
export const PUBLIC_PATHS = ['/', '/login', '/casdoor-callback', '/reset-password'] as const;
export const PUBLIC_PATHS = ['/', '/login', '/casdoor-callback', '/reset-password', '/sso/authorize'] as const;
/** 登录后首页默认跳转的 Agent ID */
export const DEFAULT_CHAT_AGENT_ID = 16;
@@ -1,15 +1,17 @@
<script setup lang="ts">
/**
* shared/layouts/AppHeaderTools.vue
* 顶栏工具区:主题与语言切换。
* 顶栏工具区:第三方系统、主题与语言切换。
*/
import ThemeToggleButton from '@/shared/components/ThemeToggleButton.vue';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import { ExternalSystemLinks } from '@/features/sso';
</script>
<template>
<div class="flex items-center gap-2">
<ExternalSystemLinks />
<ThemeToggleButton />
<LocaleToggleButton />
</div>
+1
View File
@@ -148,6 +148,7 @@ const clearAuthStorage = (): void => {
sessionStorage.removeItem(AUTH_USER_KEY);
sessionStorage.removeItem('hxops_wecom_state');
sessionStorage.removeItem('hxops_casdoor_state');
sessionStorage.removeItem('hxops_sso_continuation');
};
/**
+110
View File
@@ -0,0 +1,110 @@
# -*- coding: utf-8 -*-
"""
scripts/fill_overtime_form.py
用途:按模板批量生成指定日期区间的加班申请单 .xls。
依赖:xlrd、xlutils.copy、xlwt。
逻辑:读取模板 ABCD 列固定信息;工作日在前、周六在后,跳过周日。
"""
from datetime import date, timedelta
import xlrd
from xlutils.copy import copy
SRC = r"e:\流程\加班\加班申请单模板_202601_原.xls"
OUT = r"e:\流程\加班\加班申请单_20260721-20260820.xls"
def _date_str(d: date) -> str:
"""将 date 格式化为模板使用的 YYYY-MM-DD 字符串。"""
return d.strftime("%Y-%m-%d")
def _overtime_hours(is_weekday: bool) -> str:
"""
按时间段计算加班时数。
核心逻辑:工作日 18:00–22:30 为 4.5 小时;周六 08:00–20:00 扣午休后为 10 小时。
"""
return "4.5" if is_weekday else "10"
def build_ordered_dates(start: date, end: date) -> tuple[list[date], list[date], list[date]]:
"""
遍历日期区间:工作日(周一~周五)在前,周六在后,跳过周日。
Returns:
(ordered_dates, weekdays, saturdays)
"""
weekdays: list[date] = []
saturdays: list[date] = []
current = start
while current <= end:
wd = current.weekday()
if wd < 5:
weekdays.append(current)
elif wd == 5:
saturdays.append(current)
# 周日 (wd == 6) 跳过
current += timedelta(days=1)
return weekdays + saturdays, weekdays, saturdays
def fill_overtime_workbook(src_path: str, out_path: str, start: date, end: date) -> None:
"""
复制模板并填入加班明细。
核心逻辑:保留表头与 ABCD;工作日类型 026 / 18:00–22:30,周六类型 027 / 08:00–20:00。
"""
rb = xlrd.open_workbook(src_path, formatting_info=True)
rs = rb.sheet_by_index(0)
wb = copy(rb)
ws = wb.get_sheet(0)
dept = rs.cell_value(1, 1)
emp_no = rs.cell_value(1, 2)
name = rs.cell_value(1, 3)
ordered_dates, weekdays, saturdays = build_ordered_dates(start, end)
# [STEP 1] 清除模板旧数据行
for row_idx in range(1, rs.nrows):
for col_idx in range(rs.ncols):
ws.write(row_idx, col_idx, "")
# [STEP 2] 写入新明细
for idx, day in enumerate(ordered_dates, start=1):
is_weekday = day.weekday() < 5
ot_type = "026" if is_weekday else "027"
start_time = "18:00" if is_weekday else "08:00"
end_time = "22:30" if is_weekday else "20:00"
ds = _date_str(day)
row = idx
ws.write(row, 0, str(idx))
ws.write(row, 1, dept)
ws.write(row, 2, emp_no)
ws.write(row, 3, name)
ws.write(row, 4, ot_type)
ws.write(row, 5, ds)
ws.write(row, 6, ds)
ws.write(row, 7, start_time)
ws.write(row, 8, ds)
ws.write(row, 9, end_time)
ws.write(row, 10, _overtime_hours(is_weekday))
ws.write(row, 11, "")
wb.save(out_path)
print(f"Saved: {out_path}")
print(
f"Rows: {len(ordered_dates)} "
f"(weekdays {len(weekdays)} + saturdays {len(saturdays)})"
)
if __name__ == "__main__":
fill_overtime_workbook(
SRC,
OUT,
date(2026, 7, 21),
date(2026, 8, 20),
)