OIDC 集成指南

OIDC 集成指南

MLiev IAM 作为 OIDC 身份提供商,为第三方应用提供单点登录。

协议端点

所有端点以 /oidc/:client_id 为前缀:

端点 路径
发现文档 /.well-known/openid-configuration
授权 /authorize
令牌 /token
用户信息 /userinfo
内省 /introspect
撤销 /revoke
JWKS /jwks

创建 OIDC 客户端

curl -X POST http://localhost:8080/api/admin/applications \
  -H "Authorization: Bearer <admin_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "我的应用",
    "protocolType": "oidc",
    "protocolConfig": {
      "redirectUris": ["http://localhost:3000/callback"],
      "grantTypes": ["authorization_code", "refresh_token"],
      "scopes": ["openid", "profile", "email"],
      "clientType": "confidential"
    }
  }'

授权码流程

1. 引导用户到授权页面

/oidc/{client_id}/authorize?
  response_type=code&
  client_id={client_id}&
  redirect_uri=http://localhost:3000/callback&
  scope=openid profile email&
  state=随机字符串&
  nonce=随机字符串

2. 用户登录后重定向回应用

http://localhost:3000/callback?code=授权码&state=随机字符串

3. 用授权码换取令牌

curl -X POST /oidc/{client_id}/token \
  -d "grant_type=authorization_code\
&code=授权码\
&redirect_uri=http://localhost:3000/callback\
&client_id={client_id}\
&client_secret={client_secret}"

响应:

{
  "access_token": "...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "...",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid profile email"
}

PKCE(公开客户端推荐)

授权请求添加 code_challengecode_challenge_method=S256,令牌请求用 code_verifier 替代 client_secret

获取用户信息

curl /oidc/{client_id}/userinfo \
  -H "Authorization: Bearer {access_token}"
Scope 返回字段
openid sub
profile name, preferred_username, nickname
email email, email_verified
phone phone_number

客户端凭据流程

curl -X POST /oidc/{client_id}/token \
  -d "grant_type=client_credentials\
&client_id={client_id}\
&client_secret={client_secret}\
&scope=api"

iframe 嵌入登录

<iframe src="https://auth.example.com/auth/login?session_id=xxx"
  width="400" height="500"></iframe>
<script>
window.addEventListener('message', (e) => {
  if (e.data.type === 'oidc-login-success') {
    // 处理登录成功
  }
});
</script>

常见错误

错误 说明
invalid_client 客户端 ID/密钥错误
invalid_grant 授权码过期或已使用
invalid_scope 需包含 openid
invalid_redirect_uri URI 必须完全匹配

兼容标准

OpenID Connect Core 1.0、OAuth 2.0 (RFC 6749)、Token Introspection (RFC 7662)、Token Revocation (RFC 7009)、PKCE (RFC 7636)