主题
SSO 适配指南
1. 准备工作
在 Ksuser 开放平台中创建 SSO 内部服务应用,获取:
ClientID(client_id)ClientSecret(client_secret)- 已登记的
redirect_uri requirePkce配置(建议保持开启)
注意:
- 仅管理员账号可创建/管理 SSO 应用
- 回调地址需与登记值完全一致
- 授权请求必须包含
openid
2. 读取 OIDC Discovery
先调用:
GET https://api.ksuser.cn/.well-known/openid-configuration
重点读取:
issuerauthorization_endpointtoken_endpointuserinfo_endpointcode_challenge_methods_supported
3. 发起授权请求
将用户重定向到:
https://auth.ksuser.cn/sso/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&scope=openid%20profile%20email&state=STATE&nonce=NONCE&code_challenge=CHALLENGE&code_challenge_method=S256
参数说明:
| 参数 | 必填 | 说明 |
|---|---|---|
client_id | 是 | SSO 客户端 ID |
redirect_uri | 是 | 与登记值完全一致 |
response_type | 是 | 固定 code |
scope | 是 | 至少包含 openid |
state | 建议 | 防 CSRF |
nonce | 建议 | OIDC 防重放 |
code_challenge | PKCE 开启时必填 | code_verifier 的 S256 结果 |
code_challenge_method | PKCE 开启时必填 | 固定 S256 |
4. 用授权码换 Token
请求:
POST https://api.ksuser.cn/sso/token
application/x-www-form-urlencoded 示例:
bash
curl -X POST 'https://api.ksuser.cn/sso/token' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'code=ssocode_xxx' \
--data-urlencode 'client_id=ssoclient_xxx' \
--data-urlencode 'client_secret=ssosk_xxx' \
--data-urlencode 'redirect_uri=https://service.example.com/callback' \
--data-urlencode 'code_verifier=VERIFIER'成功示例:
json
{
"access_token": "<ACCESS_TOKEN>",
"id_token": "<ID_TOKEN>",
"token_type": "Bearer",
"expires_in": 7200,
"scope": "openid profile email"
}5. 获取 UserInfo
请求:
GET https://api.ksuser.cn/sso/userinfo
Header 传 token:
bash
curl 'https://api.ksuser.cn/sso/userinfo' \
-H 'Authorization: Bearer <ACCESS_TOKEN>'示例返回:
json
{
"sub": "sub_xxx",
"nickname": "demo_user",
"preferred_username": "demo_user",
"picture": "https://cdn.example.com/avatar.png",
"email": "demo@example.com",
"email_verified": true
}6. 错误码排查
invalid_request:参数缺失、redirect_uri不匹配、PKCE 参数不完整invalid_client:client_id无效,或client_secret错误invalid_scope:scope 不支持或不在登记范围内invalid_grant:授权码无效/过期/已消费,或code_verifier校验失败invalid_token:access_token无效或过期unsupported_response_type:response_type非codeunsupported_grant_type:grant_type非authorization_code
7. 安全建议
client_secret只保存在服务端,禁止发到浏览器- 始终校验
state、nonce - 保持
PKCE Required开启 code只用一次,回调后立即换 token