Skip to content
Bitzsoft.Integrationsbitzsoft.integrations

Reference

Keycloak IdentityProvider

Keycloak 身份提供者服务——OAuth2 client_credentials 令牌模式。

Last updated

基于 Keycloak Admin REST API 实现,采用 OAuth2 Client Credentials 令牌模式,内置令牌缓存与自动刷新。

包信息

  • NuGet 包:Bitzsoft.Integrations.IdentityProvider.Keycloak
  • 接口:IIdentityProviderService
  • 鉴权:OAuth2 client_credentials(ClientId / ClientSecret)
  • Provider ID:keycloak

配置

字段类型必填默认值说明
ClientIdstring客户端 ID
ClientSecretstring客户端密钥
BaseUrlstringhttp://localhost:8080Keycloak 服务基地址
Realmstringmaster目标 Realm 名称
HttpClientNamestringIdentityProviderKeycloak业务 HttpClient 命名
TokenHttpClientNamestringIdentityProviderKeycloakToken令牌刷新专用 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。

100%

滚轮或按钮缩放 · 放大后拖动画面 · 双击切换 100% / 200%