- IAP 反代目标从 Mac 127.0.0.1:18101/18102 搬上 K8s - 镜像 crpi-.../ssw188/nginx:iap-demo-v1.0.0: Flask 3 + gunicorn - UID 10106, ClusterIP Service app-crm-svc/app-mobile-svc:8000 - 严格按 docs/integrate-with-iap.md §7 模板, 简化: 不做 token 兑换 (IAP 已鉴权 + 注 X-Auth-Token, demo 不需要 client_secret) - env 全部明文 Deployment 注入 (无 Secret) 准备与 ipass-sso v0.7.21 nginx.conf upstream 改 K8s Service 配合. Co-Authored-By: Claude Code <[email protected]>
156 lines
5.4 KiB
Python
156 lines
5.4 KiB
Python
"""IAP demo app — 集成测试桩, 验证 /proxy/<app>/ 反代链路.
|
|
|
|
设计取舍:
|
|
- IAP 模式 = 入站鉴权 + 出站反代. demo 已经被 IAP 鉴权 + 注 X-Auth-* 头,
|
|
不需要再做 OAuth dance (那部分归 ipass-sso 的 IdP 端负责)
|
|
- 因此本 demo 不做 token 兑换, 不需要 client_secret
|
|
- 保留 /login 跳 /oauth/authorize 作为 SP-initiated 流程的可选入口
|
|
(实际 demo 不必走, 企微工作台点图标是 IdP-initiated 流程)
|
|
- /callback 收 code, 显形展示 (证明反代透传 code 成功), 跳 /me
|
|
- /me 读 IAP 注入的 X-Auth-* 头展示 (主用)
|
|
- /healthz 给 K8s probe 用
|
|
|
|
参考 docs/integrate-with-iap.md §3.5 完整 OAuth dance 模板, 真实业务 app 应照抄.
|
|
|
|
环境变量 (K8s Deployment env 注入):
|
|
IDP_BASE = https://i28868828dm.mayishangshu.cn:188
|
|
REDIRECT_URI = https://.../proxy/<app>/callback (oauth_clients.json 注册的)
|
|
BASE = /proxy/app-crm (HTML href 用; redirect() 不加)
|
|
PORT = 8000
|
|
"""
|
|
import json
|
|
import os
|
|
import secrets
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from flask import Flask, redirect, request, session
|
|
|
|
IDP = os.environ["IDP_BASE"]
|
|
REDIRECT_URI = os.environ["REDIRECT_URI"]
|
|
BASE = os.environ.get("BASE", "")
|
|
PORT = int(os.environ.get("PORT", "8000"))
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = os.environ.get("FLASK_SECRET", secrets.token_hex(32))
|
|
|
|
|
|
@app.route("/login")
|
|
def login():
|
|
"""SP-initiated 可选入口 — demo 主要走 IdP-initiated (企微工作台)."""
|
|
state = secrets.token_urlsafe(16)
|
|
session["state"] = state
|
|
qs = urllib.parse.urlencode({
|
|
"response_type": "code",
|
|
"redirect_uri": REDIRECT_URI,
|
|
"scope": "openid profile email",
|
|
"state": state,
|
|
})
|
|
return redirect(f"{IDP}/oauth/authorize?{qs}")
|
|
|
|
|
|
@app.route("/callback")
|
|
def callback():
|
|
"""IdP 把 code 投到这里 — 收到即跳 /me, 不做 token 兑换 (见 docstring).
|
|
|
|
真实 app 应: 验 state → /oauth/v20/token 换 token → 写 session → 跳 /me.
|
|
本 demo 省略 token 兑换, 因为 IAP 已鉴权 + 注 X-Auth-Token, /me 直接用.
|
|
"""
|
|
code = request.args.get("code", "")
|
|
state = request.args.get("state", "")
|
|
received = state
|
|
if received and received != session.get("state"):
|
|
return "state 不匹配", 400
|
|
if not code:
|
|
return "no code", 400
|
|
# 把 code 暂存 session, 跳 /me 看 IAP 注的头
|
|
session["last_code"] = code[:16] + "..." if len(code) > 16 else code
|
|
return redirect("/me") # 裸路径, IAP proxy_redirect 加 BASE
|
|
|
|
|
|
@app.route("/")
|
|
def home():
|
|
"""IAP 已鉴权 + 注 X-Auth-* 头. 直接读."""
|
|
user = request.headers.get("X-Auth-User", "?")
|
|
email = request.headers.get("X-Auth-Email", "")
|
|
groups = request.headers.get("X-Auth-Groups", "")
|
|
last_code = session.get("last_code", "")
|
|
return f"""<!doctype html>
|
|
<html><head><meta charset="utf-8"><title>{BASE} demo</title></head>
|
|
<body>
|
|
<h1>iap-demo @ {BASE}</h1>
|
|
<p>已登录: <b>{user}</b> ({email}) — 组: {groups}</p>
|
|
<p>最近收到 code: <code>{last_code or '(无, 走 /login 或企微入口)'}</code></p>
|
|
<ul>
|
|
<li><a href="{BASE}/me">/me (X-Auth-* 头 + 试 /oauth/userinfo)</a></li>
|
|
<li><a href="{BASE}/customers">/customers</a></li>
|
|
<li><a href="{BASE}/about">/about</a></li>
|
|
<li><a href="{BASE}/login">/login (SP-initiated)</a></li>
|
|
</ul>
|
|
<h3>request.headers</h3>
|
|
<pre style="background:#f4f4f4;padding:.5em;font-size:11px">{json.dumps(dict(request.headers), indent=2, ensure_ascii=False)}</pre>
|
|
</body></html>
|
|
"""
|
|
|
|
|
|
@app.route("/me")
|
|
def me():
|
|
"""读 IAP 注入的 X-Auth-* 头. 试调 /oauth/userinfo (用 X-Auth-Token 当 Bearer),
|
|
失败则降级展示原始头 (X-Auth-Token 是 JWT session 而非 OAuth access_token 时常见)."""
|
|
tok = request.headers.get("X-Auth-Token", "")
|
|
userinfo_result = None
|
|
userinfo_err = None
|
|
if tok:
|
|
try:
|
|
req = urllib.request.Request(
|
|
f"{IDP}/oauth/userinfo",
|
|
headers={"Authorization": f"Bearer {tok}"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=5) as r:
|
|
userinfo_result = json.loads(r.read())
|
|
except Exception as e:
|
|
userinfo_err = f"{type(e).__name__}: {e}"
|
|
|
|
auth_headers = {k: v for k, v in request.headers.items() if k.lower().startswith("x-auth-")}
|
|
out = {
|
|
"iap": "ok" if request.headers.get("X-Auth-User") else "no X-Auth-User",
|
|
"auth_headers": auth_headers,
|
|
"oauth_userinfo": userinfo_result,
|
|
"oauth_userinfo_error": userinfo_err,
|
|
}
|
|
return (
|
|
f"<pre>{json.dumps(out, indent=2, ensure_ascii=False)}</pre>",
|
|
200,
|
|
{"Content-Type": "text/html; charset=utf-8"},
|
|
)
|
|
|
|
|
|
@app.route("/customers")
|
|
def customers():
|
|
return (
|
|
json.dumps({"app": BASE, "page": "customers", "rows": [
|
|
{"id": 1, "name": "Acme Corp"}, {"id": 2, "name": "Globex"},
|
|
]}, ensure_ascii=False),
|
|
200,
|
|
{"Content-Type": "application/json"},
|
|
)
|
|
|
|
|
|
@app.route("/about")
|
|
def about():
|
|
return (
|
|
json.dumps({"app": BASE, "note": "iap-demo — K8s 部署, 验证反代 + 头注入"}, ensure_ascii=False),
|
|
200,
|
|
{"Content-Type": "application/json"},
|
|
)
|
|
|
|
|
|
@app.route("/healthz")
|
|
def healthz():
|
|
return {"ok": True, "base": BASE}, 200, {"Content-Type": "application/json"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# 0.0.0.0 — IAP 容器要能连进来 (不能 127.0.0.1)
|
|
app.run(host="0.0.0.0", port=PORT, debug=False)
|