Keycloak API 接口文档

概述

本文档总结了程序中使用的所有 Keycloak 接口,包括认证、用户管理和令牌管理相关的 API。

接口列表

1. 用户认证接口

1.1 用户登录

  • 接口地址: POST /realms/{realm}/protocol/openid-connect/token
  • 功能描述: 用户密码认证,获取访问令牌
  • 请求方式: POST
  • Content-Type: application/x-www-form-urlencoded

请求参数:

grant_type: password
client_id: {客户端ID}
client_secret: {客户端密钥}
username: {用户名}
password: {密码}

响应示例:

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 300,
  "refresh_expires_in": 1800,
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "12345678-1234-1234-1234-123456789012",
  "scope": "openid profile email"
}

错误响应:

  • 401 Unauthorized: 用户名或密码错误
  • 400 Bad Request: 请求参数无效
  • 5xx Server Error: 认证服务不可用

1.2 刷新令牌

  • 接口地址: POST /realms/{realm}/protocol/openid-connect/token
  • 功能描述: 使用刷新令牌获取新的访问令牌
  • 请求方式: POST
  • Content-Type: application/x-www-form-urlencoded

请求参数:

grant_type: refresh_token
client_id: {客户端ID}
client_secret: {客户端密钥}
refresh_token: {刷新令牌}

响应示例:

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 300,
  "refresh_expires_in": 1800,
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "12345678-1234-1234-1234-123456789012",
  "scope": "openid profile email"
}

错误响应:

  • 401 Unauthorized: 刷新令牌无效或已过期
  • 400 Bad Request: 请求参数无效

2. 管理员 API 接口

2.1 获取管理员令牌

  • 接口地址: POST /realms/master/protocol/openid-connect/token
  • 功能描述: 获取管理员访问令牌,用于调用管理 API
  • 请求方式: POST
  • Content-Type: application/x-www-form-urlencoded

请求参数:

grant_type: password
client_id: admin-cli
username: admin
password: admin

响应示例:

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 60,
  "refresh_expires_in": 1800,
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "12345678-1234-1234-1234-123456789012",
  "scope": "openid profile email"
}

2.2 获取用户列表

  • 接口地址: GET /admin/realms/{realm}/users
  • 功能描述: 获取指定域下的所有用户信息
  • 请求方式: GET
  • 认证方式: Bearer Token(管理员令牌)
  • Content-Type: application/json

请求头:

Authorization: Bearer {管理员访问令牌}
Content-Type: application/json

响应示例:

[
  {
    "id": "12345678-1234-1234-1234-123456789012",
    "createdTimestamp": 1623456789000,
    "username": "testuser",
    "enabled": true,
    "totp": false,
    "emailVerified": true,
    "firstName": "Test",
    "lastName": "User",
    "email": "test@example.com",
    "attributes": {},
    "disableableCredentialTypes": [],
    "requiredActions": [],
    "notBefore": 0,
    "access": {}
  }
]

2.3 根据用户ID查询用户信息

  • 接口地址: GET /admin/realms/{realm}/users/{userId}
  • 功能描述: 根据用户ID获取单个用户的详细信息
  • 请求方式: GET
  • 认证方式: Bearer Token(管理员令牌)
  • Content-Type: application/json

请求头:

Authorization: Bearer {管理员访问令牌}
Content-Type: application/json

路径参数:

  • userId: 用户的唯一标识符 (UUID)

响应示例:

{
  "id": "12345678-1234-1234-1234-123456789012",
  "createdTimestamp": 1623456789000,
  "username": "testuser",
  "enabled": true,
  "totp": false,
  "emailVerified": true,
  "firstName": "Test",
  "lastName": "User",
  "email": "test@example.com",
  "attributes": {},
  "disableableCredentialTypes": [],
  "requiredActions": [],
  "notBefore": 0,
  "access": {}
}

数据模型

KeycloakTokenResponse

{
  "access_token": "string",          // 访问令牌
  "expires_in": "number",            // 访问令牌过期时间(秒)
  "refresh_expires_in": "number",    // 刷新令牌过期时间(秒)
  "refresh_token": "string",         // 刷新令牌
  "token_type": "string",            // 令牌类型,通常为 "Bearer"
  "not-before-policy": "number",     // 不早于策略时间戳
  "session_state": "string",         // 会话状态标识
  "scope": "string"                  // 令牌作用域
}

KeycloakUserResponse

{
  "id": "string",                    // 用户唯一标识符 (UUID)
  "createdTimestamp": "number",      // 创建时间戳
  "username": "string",              // 用户名
  "enabled": "boolean",              // 是否启用
  "totp": "boolean",                 // 是否启用双因子认证
  "emailVerified": "boolean",        // 邮箱是否验证
  "firstName": "string",             // 名
  "lastName": "string",              // 姓
  "email": "string",                 // 邮箱地址
  "attributes": "object",            // 用户属性
  "disableableCredentialTypes": [],  // 可禁用的凭据类型
  "requiredActions": [],             // 必需操作
  "notBefore": "number",             // 不早于时间戳
  "access": "object"                 // 访问权限
}

UserInfo(程序内部模型)

{
  "keycloakUserId": "UUID",          // Keycloak 用户ID
  "username": "string",              // 用户名
  "email": "string"                  // 邮箱地址
}

配置参数

程序中使用的 Keycloak 配置参数:

# Keycloak 基础配置
keycloak.base-url=http://localhost:8080
keycloak.realm=yun-platform

# OAuth2 客户端配置
spring.security.oauth2.client.registration.keycloak.client-id=your-client-id
spring.security.oauth2.client.registration.keycloak.client-secret=your-client-secret

# JWT 资源服务器配置
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/yun-platform
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8080/realms/yun-platform/protocol/openid_connect/certs

使用示例

1. 用户登录流程

// 1. 调用登录接口
KeycloakTokenResponse tokenResponse = keycloakService.login(username, password);

// 2. 从响应中获取访问令牌
String accessToken = tokenResponse.getAccessToken();

// 3. 解析访问令牌获取用户信息
Jwt jwt = jwtDecoder.decode(accessToken);
String userId = jwt.getSubject();
String username = jwt.getClaim("preferred_username");

2. 获取用户列表流程

// 1. 获取管理员令牌
String adminToken = getAdminToken();

// 2. 调用用户列表接口
List<UserInfo> userList = keycloakService.getUserList();

3. 查询用户信息流程

// 1. 通过用户ID查询详细信息
UUID userId = UUID.fromString("user-id");
KeycloakUserResponse userInfo = keycloakService.getUserInfo(userId);

// 2. 获取用户全名
String fullName = userInfo.getFullName(); // lastName + " " + firstName

错误处理

常见错误码和处理方式:

HTTP状态码错误说明处理方式
400请求参数无效检查请求参数格式和必填项
401认证失败检查用户名密码或令牌有效性
403权限不足检查用户角色和权限配置
404用户不存在验证用户ID是否正确
500服务器内部错误检查 Keycloak 服务状态

异常处理示例:

try {
    KeycloakTokenResponse response = keycloakService.login(username, password);
} catch (RuntimeException e) {
    if (e.getMessage().contains("用户名或密码错误")) {
        // 处理认证失败
    } else if (e.getMessage().contains("认证服务不可用")) {
        // 处理服务不可用
    }
}

安全建议

  1. 令牌管理:

    • 妥善保存访问令牌和刷新令牌
    • 定期刷新访问令牌
    • 在适当时机清除过期令牌
  2. 权限控制:

    • 仅在必要时使用管理员权限
    • 对敏感操作进行权限验证
  3. 配置安全:

    • 使用环境变量管理敏感配置
    • 在生产环境中使用 HTTPS
    • 定期更新客户端密钥
  4. 日志监控:

    • 记录认证失败事件
    • 监控异常的令牌使用模式
    • 设置适当的日志级别
最后修改:2025 年 06 月 16 日
如果觉得我的文章对你有用,请随意赞赏