fix: 小程序服务号绑定先打开门户域名再跳转微信授权。

web-view 不能直接打开 open.weixin.qq.com,移动端改为打开已配置的业务域名中转页。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-10-29 01:44:40 +08:00
1 parent 459b820f95
commit e7c1762113
7 files changed
+137 -8

No files matched your search

+50
View File
@@ -1,5 +1,6 @@
"""本人服务号绑定;OAuth 回调仅暂存候选,不直接绑定、不授予门户登录。"""
from html import escape
import json
from pathlib import Path
import secrets
from typing import Literal, Optional
@@ -49,6 +50,17 @@ def remove(user: dict = Depends(get_current_user), db: Session = Depends(get_db)
return success_response(svc.unbind(db, user))
@router.get("/public/wechat-notices/oauth/launch", response_class=HTMLResponse)
def oauth_launch(state: str = Query(default="")):
"""小程序 web-view 入口。先由业务域名打开本页,再跳到微信授权。"""
try:
target = svc.resolve_mobile_authorize_target(state)
except HTTPException as exc:
message = exc.detail if isinstance(exc.detail, str) else "授权页面打开失败,请返回小程序重试"
return _binding_message_page(message)
return _oauth_redirect_page(target)
@router.get("/public/wechat-notices/oauth/callback", response_class=HTMLResponse)
def callback(state: str = Query(min_length=20, max_length=100), code: str = Query(min_length=1, max_length=512)):
try:
@@ -68,6 +80,44 @@ def callback(state: str = Query(min_length=20, max_length=100), code: str = Quer
)
def _page_headers(nonce):
return {
"Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
"Content-Security-Policy": (
"default-src 'none'; frame-ancestors 'none'; base-uri 'none'; "
f"script-src 'nonce-{nonce}'; style-src 'nonce-{nonce}'"
),
}
def _binding_message_page(message):
nonce = secrets.token_urlsafe(24)
return HTMLResponse(
'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
'<meta name="referrer" content="no-referrer"><title>微信授权</title>'
f'<style nonce="{nonce}">body{{font:16px/1.6 sans-serif;color:#444;padding:24px}}</style>'
f'<body><p>{escape(message)}</p></body></html>',
status_code=200,
headers=_page_headers(nonce),
)
def _oauth_redirect_page(target):
nonce = secrets.token_urlsafe(24)
payload = json.dumps(target).replace("<", "\\u003c")
return HTMLResponse(
'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
'<meta name="referrer" content="no-referrer"><title>微信授权</title>'
f'<body><p>正在打开微信授权…</p>'
f'<style nonce="{nonce}">body{{font:16px/1.6 sans-serif;color:#444;padding:24px}}</style>'
f'<script nonce="{nonce}">location.replace({payload})</script></body></html>',
status_code=200,
headers=_page_headers(nonce),
)
def mobile_callback_page(subscribed: bool):
"""只返回原小程序;真实绑定仍由原登录客户端提交并显示最终结果。"""
nonce = secrets.token_urlsafe(24)
+1
View File
@@ -206,6 +206,7 @@ class Settings(BaseSettings):
"/api/web/auth/refresh-token,"
"/api/web/auth/mp-webview-exchange,"
"/api/public/wechat-notices/oauth/callback,"
"/api/public/wechat-notices/oauth/launch,"
"/api/web/admin/attachment/upload,"
"/api/web/doclib/upload,"
"/api/web/admin/products/upload-image,"
+28 -1
View File
@@ -1,5 +1,6 @@
"""服务号身份绑定:扫码候选 + 原登录端确认,两步均在短时会话内完成。"""
import json
import re
import secrets
import time
from urllib.parse import urlencode, urlparse
@@ -15,6 +16,7 @@ from app.models.wechat_notice import WechatBinding
from app.services.wechat_oa_client import client, WechatAPIError
TTL = 300
_STATE_RE = re.compile(r"^[A-Za-z0-9_-]{20,100}$")
_GETDEL = "local v=redis.call('GET',KEYS[1]); redis.call('DEL',KEYS[1]); return v"
_UNLOCK = "if redis.call('GET',KEYS[1]) == ARGV[1] then return redis.call('DEL',KEYS[1]) end return 0"
@@ -125,10 +127,35 @@ def _start_binding(user, *, mode="desktop"):
_save(session_id, data)
_call("set", "wechat:oa:state:" + state, session_id, ex=TTL)
_call("set", _owner_key(user), session_id, ex=TTL)
# 小程序 web-view 只能打开已配置的业务域名。open.weixin.qq.com 不能作为 src,
# 移动端先打开门户中转页,再由该页跳到微信授权;电脑扫码仍直接使用授权链接。
authorize_url = mobile_launch_url(state) if mode == "mobile" else oauth_authorize_url(state)
return {"sessionId": session_id, "authorizeUrl": authorize_url, "expiresIn": TTL}
def oauth_authorize_url(state):
callback = settings.WECHAT_OA_PUBLIC_BASE_URL.rstrip("/") + settings.API_V1_PREFIX + "/public/wechat-notices/oauth/callback"
params = {"appid": settings.WECHAT_OA_APPID, "redirect_uri": callback,
"response_type": "code", "scope": "snsapi_base", "state": state}
return {"sessionId": session_id, "authorizeUrl": "https://open.weixin.qq.com/connect/oauth2/authorize?" + urlencode(params) + "#wechat_redirect", "expiresIn": TTL}
return "https://open.weixin.qq.com/connect/oauth2/authorize?" + urlencode(params) + "#wechat_redirect"
def mobile_launch_url(state):
base = settings.WECHAT_OA_PUBLIC_BASE_URL.rstrip("/") + settings.API_V1_PREFIX
return base + "/public/wechat-notices/oauth/launch?" + urlencode({"state": state})
def resolve_mobile_authorize_target(state):
"""校验尚未消费的 state,返回官方授权地址。不删除 state,授权回调才消费。"""
if not _STATE_RE.fullmatch(state or ""):
raise HTTPException(400, "授权链接无效,请返回小程序重新绑定")
if not enabled():
raise HTTPException(503, "服务号通知尚未配置启用")
raw = _call("get", "wechat:oa:state:" + state)
session_id = _decode(raw) if raw else ""
if not session_id or not _load(session_id):
raise HTTPException(400, "授权已过期,请返回小程序重新绑定")
return oauth_authorize_url(state)
def oauth_callback(state, code):
@@ -174,6 +174,32 @@ def test_callback_instructs_mobile_return_without_binding(binding, monkeypatch):
assert response.headers['referrer-policy'] == 'no-referrer'
def test_mobile_web_view_opens_business_domain_before_wechat(binding):
from app.api.wechat_notices import oauth_launch
from urllib.parse import parse_qs, urlparse
svc, _, redis, user, _ = binding
started = svc.start_binding(user, mode='mobile')
launch = urlparse(started['authorizeUrl'])
assert launch.scheme == 'https'
assert launch.netloc == 'portal.example.test'
assert launch.path == '/api/public/wechat-notices/oauth/launch'
assert 'open.weixin.qq.com' not in started['authorizeUrl']
state = parse_qs(launch.query)['state'][0]
page = oauth_launch(state)
body = page.body.decode()
assert 'location.replace' in body
assert 'open.weixin.qq.com/connect/oauth2/authorize' in body
assert state in body
assert "'unsafe-inline'" not in page.headers['content-security-policy']
assert redis.get('wechat:oa:state:' + state)
missing = oauth_launch('a' * 32)
assert '过期' in missing.body.decode()
assert 'open.weixin.qq.com' not in missing.body.decode()
invalid = oauth_launch('javascript:alert(1)')
assert '无效' in invalid.body.decode()
assert 'open.weixin.qq.com' not in invalid.body.decode()
def test_mobile_callback_only_returns_to_original_authenticated_client(binding):
from app.api.wechat_notices import callback, start, StartBinding
from urllib.parse import urlparse, parse_qs