跳转到内容

SSO 适配指南

1. 准备工作

在 Ksuser 开放平台中创建 SSO 内部服务应用,获取:

  • ClientIDclient_id
  • ClientSecretclient_secret
  • 已登记的 redirect_uri
  • requirePkce 配置(建议保持开启)

注意:

  • 仅管理员账号可创建/管理 SSO 应用
  • 回调地址需与登记值完全一致
  • 授权请求必须包含 openid

2. 读取 OIDC Discovery

先调用:

GET https://api.ksuser.cn/.well-known/openid-configuration

重点读取:

  • issuer
  • authorization_endpoint
  • token_endpoint
  • userinfo_endpoint
  • code_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_idSSO 客户端 ID
redirect_uri与登记值完全一致
response_type固定 code
scope至少包含 openid
state建议防 CSRF
nonce建议OIDC 防重放
code_challengePKCE 开启时必填code_verifierS256 结果
code_challenge_methodPKCE 开启时必填固定 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_clientclient_id 无效,或 client_secret 错误
  • invalid_scope:scope 不支持或不在登记范围内
  • invalid_grant:授权码无效/过期/已消费,或 code_verifier 校验失败
  • invalid_tokenaccess_token 无效或过期
  • unsupported_response_typeresponse_typecode
  • unsupported_grant_typegrant_typeauthorization_code

7. 安全建议

  • client_secret 只保存在服务端,禁止发到浏览器
  • 始终校验 statenonce
  • 保持 PKCE Required 开启
  • code 只用一次,回调后立即换 token