基于 Keycloak Admin REST API 实现,采用 OAuth2 Client Credentials 令牌模式,内置令牌缓存与自动刷新。
包信息
- NuGet 包:
Bitzsoft.Integrations.IdentityProvider.Keycloak - 接口:
IIdentityProviderService - 鉴权:OAuth2 client_credentials(ClientId / ClientSecret)
- Provider ID:
keycloak
配置
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
ClientId | string | 是 | — | 客户端 ID |
ClientSecret | string | 是 | — | 客户端密钥 |
BaseUrl | string | 否 | http://localhost:8080 | Keycloak 服务基地址 |
Realm | string | 否 | master | 目标 Realm 名称 |
HttpClientName | string | 否 | IdentityProviderKeycloak | 业务 HttpClient 命名 |
TokenHttpClientName | string | 否 | IdentityProviderKeycloakToken | 令牌刷新专用 HttpClient 命名 |
{ "IdentityProvider": { "Keycloak": { "ClientId": "admin-cli", "ClientSecret": "your-client-secret", "BaseUrl": "http://localhost:8080", "Realm": "master" } }}注册
// 方式一:IConfiguration(默认读取 "IdentityProvider:Keycloak" 配置节)services.AddKeycloakIdentityProvider(configuration);
// 方式二:委托配置services.AddKeycloakIdentityProvider(options =>{ options.ClientId = "admin-cli"; options.ClientSecret = "your-client-secret"; options.BaseUrl = "http://localhost:8080"; options.Realm = "master";});使用示例
// 创建用户var user = await idp.CreateUserAsync(new CreateUserRequest{ FirstName = "Bob", LastName = "Li", Email = "bob@example.com", Login = "bob"});
// 重置密码(传新密码直接设置,留空发送重置邮件)await idp.ResetPasswordAsync(user.UserId, "NewP@ssw0rd!");
// 用户组管理await idp.AddUserToGroupAsync(new UserGroupRequest{ UserId = user.UserId, GroupId = "engineering-group-id"});
var groups = await idp.ListGroupsAsync();
// 删除用户await idp.DeleteUserAsync(user.UserId);鉴权机制
- 令牌获取:POST
/realms/{realm}/protocol/openid-connect/token,form-urlencoded,grant_type=client_credentials。 - 令牌缓存:
KeycloakTokenManager为 Singleton,过期前 5 分钟刷新。 - 业务请求:按请求注入
Authorization: Bearer {token}头,访问/admin/realms/{realm}/...端点。 - 双 HttpClient 隔离:令牌刷新 HttpClient 不经业务管道。
已知限制
凭据需在目标 Realm 下创建 Confidential Client 并开启 Service Accounts Enabled。Provider 注册为 Transient。