Skip to content

Keycloak C# High Level Client

This a documentation on how to use the Keycloak client in C# to communicate with a Keycloak application.

Installation

To install the Keycloak.Net library, run the following command in the terminal:

dotnet add package Keycloak.Net
  1. Add the Keycloak settings to your appsettings.json file:

    {
        "Keycloak": {
            "ServerUrl": "https://your-keycloak-server/auth",
            "RealmName": "your-realm-name",
            "AdminUsername": "your-admin-username",
            "AdminPassword": "your-admin-password"
        }
    }
    
  2. Optionally, create configuration class to hold the Keycloak settings:

    public class KeycloakClientOptions
    {
        public string Url { get; set; }
        public string RealmName { get; set; }
        public string AdminUserName { get; set; }
        public string AdminPassword { get; set; }
    }
    
  3. Configure your options with KeycloakOptions on your module project and then register it.

    [DependsOn(
        //...other dependencies
        typeof(AbpAutofacModule) // <-- Prerequisite
    )]
    public class YourModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
    
            Configure<KeycloakClientOptions>(options =>
            {
                options.Url = configuration["Keycloak:Url"];
                options.AdminUserName = configuration["Keycloak:AdminUsername"];
                options.AdminPassword = configuration["Keycloak:AdminPassword"];
                options.RealmName = configuration["Keycloak:RealmName"];
            });
        }
    }
    

Usage

Inject the IKeycloakClient into your service or controller:

public class KeycloakDataSeeder : ITransientDependency
{  
    private readonly KeycloakClient _keycloakClient;
    private readonly KeycloakClientOptions _keycloakOptions;

    public KeycloakDataSeeder(IOptions<KeycloakClientOptions> keycloakClientOptions)
    {
         _keycloakOptions = keycloakClientOptions.Value;

         _keycloakClient = new KeycloakClient(
             _keycloakOptions.Url,
             _keycloakOptions.AdminUserName,
             _keycloakOptions.AdminPassword
         );
     } 

     private async Task CreateWebClientAsync()
     {
         var webClientId = "PSSX_Web";
         var webClient = (await _keycloakClient.GetClientsAsync(_keycloakOptions.RealmName, clientId: webClientId)).FirstOrDefault();

         if (webClient == null)
         {
             var webRootUrl = "https://localhost:44322"
             webClient = new Client
             {
                 ClientId = webClientId,
                 Name = "Web Client",
                 Protocol = "openid-connect",
                 Enabled = true,
                 BaseUrl = webRootUrl,
                 RedirectUris = new List<string>
                 {
                     $"{webRootUrl}signin-oidc"
                 },
                 ImplicitFlowEnabled = true,  // for hybrid flow
                 FrontChannelLogout = true,
                 PublicClient = false,
                 Secret = "1q2w3e*"
             };
             webClient.Attributes = new Dictionary<string, object>
             {
                 { "post.logout.redirect.uris", $"{webRootUrl}signout-callback-oidc" }
             };

             await _keycloakClient.CreateClientAsync(_keycloakOptions.RealmName, webClient);
         }
     }
}  

This documentation should help you set up and use the Keycloak client in your C# project. If you have any specific questions or need further assistance, feel free to ask!