Common.Keycloak.Lib
1.0.5
dotnet add package Common.Keycloak.Lib --version 1.0.5
NuGet\Install-Package Common.Keycloak.Lib -Version 1.0.5
<PackageReference Include="Common.Keycloak.Lib" Version="1.0.5" />
<PackageVersion Include="Common.Keycloak.Lib" Version="1.0.5" />
<PackageReference Include="Common.Keycloak.Lib" />
paket add Common.Keycloak.Lib --version 1.0.5
#r "nuget: Common.Keycloak.Lib, 1.0.5"
#:package Common.Keycloak.Lib@1.0.5
#addin nuget:?package=Common.Keycloak.Lib&version=1.0.5
#tool nuget:?package=Common.Keycloak.Lib&version=1.0.5
Common Keycloak Client Factory
This repository provides a Keycloak client factory for managing Keycloak operations, including authentication, token management, and client creation. The factory handles the configuration and initialization of various Keycloak clients for interacting with realms, users, roles, groups, and client role mappings.
Table of Contents
- Overview
- Structure
- Installation
- Usage
- Key Clients and Operations
- Example Code Snippets
- Dependencies
- License
Overview
The Common Keycloak Client Factory simplifies integration with Keycloak by providing pre-configured HTTP clients for various operations. It includes support for client credentials authentication, caching, and secure HTTP communication.
Structure
The repository is organized as follows:
Top-level Directory: Common.Keycloak
Contains key components for managing Keycloak operations:
ApiSpec/- API specifications and documentationClientFactory/- Implementation of the Keycloak client factoryConfiguration/- Configuration classes and settingsGeneratedClient/- Auto-generated clients for Keycloak operations
Other essential files include:
Common.Keycloak.csproj- Project configuration fileLICENSE.txt- License for the projectnswag.json- NSwag configuration for generating API clients
Installation
To set up the Keycloak client factory, follow these steps:
Clone the repository:
git clone <repository-url> cd <repository-folder>Install the required dependencies:
dotnet restoreConfigure the application settings for Keycloak (e.g., base URL, client ID, and secret).
Build the project:
dotnet build
Usage
The factory provides methods to create various Keycloak clients and retrieve user details from tokens.
Example Code: Creating a Users Client
var usersClient = await keycloakClientFactory.CreateUsersClientAsync(isAdmin: true);
Example Code: Retrieving User Details from a Token
var userDetails = await keycloakClientFactory.GetUserDetailsFromToken();
Console.WriteLine($"User ID: {userDetails.UserId}, Realm: {userDetails.RealmName}");
Key Clients and Operations
RealmsAdminClient
- Manages Keycloak realms.
UsersClient
- Handles user operations such as creating, updating, and deleting users.
GroupsClient
- Manages user groups within Keycloak.
RolesClient
- Handles role operations, including role creation and assignment.
ClientsClient
- Manages client configurations and roles.
ClientRoleMappingsClient
- Handles role mappings for clients.
Example Code Snippets
Creating a Users Client
public async ValueTask<UsersClient> CreateUsersClientAsync(bool isAdmin)
{
var httpClient = _httpClientFactory.CreateClient();
await ConfigureHttpClient(httpClient, isAdmin);
return new UsersClient(httpClient);
}
Retrieving a Token
private async Task<TokenResponse> GetTokenAsync()
{
using var tokenRequest = new HttpRequestMessage(HttpMethod.Post, _adminConfig.KeycloakAuthTokenUrl);
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", _adminConfig.ClientId },
{ "client_secret", _adminConfig.ClientSecret }
});
using var response = await _httpClientFactory.CreateClient().SendAsync(tokenRequest);
response.EnsureSuccessStatusCode();
var tokenJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TokenResponse>(tokenJson);
}
Configuring the HTTP Client
private async ValueTask ConfigureHttpClient(HttpClient httpClient, bool isAdmin = false)
{
var tokenResponse = await GetTokenAsync();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken);
httpClient.BaseAddress = new Uri(_adminConfig.KeycloakAdminUrl);
}
Dependencies
The project uses the following libraries:
- Microsoft.Extensions.Configuration - Configuration management
- Microsoft.Extensions.Http - HTTP client management
- Polly.Extensions.Http - Resilience and transient fault handling for HTTP requests
- System.IdentityModel.Tokens.Jwt - JWT handling
- System.Runtime.Caching - Caching support
- NSwag.MSBuild - API client generation using NSwag
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Common.Infrastructure.Lib (>= 1.0.4)
- Microsoft.Extensions.Configuration (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Http.Polly (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
- Polly.Extensions.Http (>= 3.0.0)
- System.IdentityModel.Tokens.Jwt (>= 7.2.0)
- System.Runtime.Caching (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.