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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Common.Keycloak.Lib" Version="1.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Common.Keycloak.Lib" Version="1.0.5" />
                    
Directory.Packages.props
<PackageReference Include="Common.Keycloak.Lib" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Common.Keycloak.Lib --version 1.0.5
                    
#r "nuget: Common.Keycloak.Lib, 1.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Common.Keycloak.Lib@1.0.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Common.Keycloak.Lib&version=1.0.5
                    
Install as a Cake Addin
#tool nuget:?package=Common.Keycloak.Lib&version=1.0.5
                    
Install as a Cake Tool

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

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 documentation
  • ClientFactory/ - Implementation of the Keycloak client factory
  • Configuration/ - Configuration classes and settings
  • GeneratedClient/ - Auto-generated clients for Keycloak operations

Other essential files include:

  • Common.Keycloak.csproj - Project configuration file
  • LICENSE.txt - License for the project
  • nswag.json - NSwag configuration for generating API clients

Installation

To set up the Keycloak client factory, follow these steps:

  1. Clone the repository:

    git clone <repository-url>
    cd <repository-folder>
    
  2. Install the required dependencies:

    dotnet restore
    
  3. Configure the application settings for Keycloak (e.g., base URL, client ID, and secret).

  4. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.5 89 3/11/2026
1.0.4 541 11/8/2024
1.0.3 768 10/22/2024
1.0.2 176 10/15/2024
1.0.1 167 10/11/2024