Introduction

When it comes to authentication and authorization in modern applications, many teams’ first reaction is to reach for paid cloud solutions β€” Azure Entra ID, AWS Cognito, Auth0 or Firebase Auth. They are excellent services, but they carry costs that can surprise you as the user base grows: plans priced per MAU (Monthly Active Users), token limits, charges for social login and MFA. In many scenarios, especially startups, personal projects, on-premises environments and companies that value data sovereignty, there is a free, open-source, enterprise-grade alternative that deserves full attention: Keycloak.

Keycloak is an identity and access management server maintained by the Cloud Native Computing Foundation (CNCF) as an incubating project, originally created by Red Hat. It implements the OAuth 2.0, OpenID Connect and SAML 2.0 protocols β€” the same ones used by Azure Entra ID, Google and other identity providers β€” but it runs on your infrastructure, with no licensing costs, no user limits and full control over the data. If you already understand the fundamentals of authentication and authorization with JWT, OAuth2 and OpenID Connect, you are ready for the next step: getting a complete identity provider running with Docker or Podman and integrating it with your ASP.NET Core application using C# 8.0+.

In this article, I run Keycloak in a container, configure a realm and a client, integrate it with a REST API in C#, customize the login page with a custom logo and theme, and compare it with the main cloud identity providers. The focus is practical, functional and 100% free.

πŸ’‘ Tip: Although the examples in this article use C# with ASP.NET Core, Keycloak is language- and framework-agnostic. Because it implements open protocols (OAuth 2.0, OpenID Connect, SAML 2.0), it works with any technology that supports these standards β€” including Java/Spring Boot, Python/Django/Flask/FastAPI, Node.js/Express/NestJS, Go, PHP/Laravel, Ruby on Rails, Rust and Angular/React/Vue on the front end. The Keycloak container setup and the realm/client configuration are identical regardless of your application’s language.

πŸ“¦ Source code: The complete implementation of this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.

Why Choose Keycloak?

Zero Cost vs Cloud Providers

The main argument in favor of Keycloak is simple: it costs nothing. While cloud providers charge per active user or per premium feature, Keycloak offers everything for free:

FeatureKeycloak (Free)Azure Entra IDAWS CognitoAuth0
Base cost$0Free up to 50,000 MAU (External ID)Free up to 50,000 MAUFree up to 7,500 MAU
Unlimited usersβœ…βŒ (charges past the limit)❌ (charges past the limit)❌ (charges past the limit)
Social loginβœ… Unlimitedβœ…βœ…βœ… (limited on free tier)
MFA (Multi-Factor)βœ… Includedβœ…βœ… (extra cost for SMS)βœ… (limited on free tier)
SAML + OIDCβœ… Bothβœ… Bothβœ… OIDC / ⚠️ limited SAMLβœ… Both
UI customizationβœ… Full (FreeMarker themes)⚠️ Limited⚠️ Limitedβœ… (paid plans)
Self-hostedβœ… Required❌ SaaS only❌ SaaS only⚠️ Enterprise plan
Data sovereigntyβœ… Full❌ Data at Microsoft❌ Data at AWS❌ Data at Auth0

πŸ’‘ Tip: Keycloak does not necessarily replace cloud providers in every scenario. If your company is already in the Azure ecosystem and needs native integration with Microsoft 365, Teams and Entra ID, Azure Entra remains the best choice. Keycloak shines when you need full control, predictable (zero) cost and vendor independence.

Main Features

Keycloak includes features that cloud providers charge for separately:

  • Single Sign-On (SSO) β€” a single login across multiple applications
  • Identity Brokering β€” federation with external providers (Google, GitHub, Facebook, Azure AD, SAML)
  • User Federation β€” integration with LDAP and Active Directory
  • Fine-grained Authorization β€” authorization policies based on roles, groups, scopes and resources
  • Multi-Factor Authentication (MFA) β€” TOTP, WebAuthn/FIDO2, SMS, email
  • Account Management Console β€” a self-service portal where users manage their profile, sessions and 2FA
  • Admin Console β€” a complete web panel to manage realms, clients, users and roles
  • Event Logging and Audit Trail β€” detailed logging of authentication events
  • REST API for Administration β€” full automation via API
  • Extensibility via SPI β€” Service Provider Interfaces for advanced customizations

Prerequisites

Keycloak in a Container: Complete Setup

Docker Compose for Development

The fastest and recommended way to run Keycloak locally is in a container. I use docker-compose with PostgreSQL as the database (the same database you would use in production):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# docker-compose.keycloak.yml
services:
  keycloak-postgres:
    image: postgres:16-alpine
    container_name: keycloak-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: keycloak-dev-123
      TZ: America/Sao_Paulo
    volumes:
      - keycloak-pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U keycloak -d keycloak"]
      interval: 10s
      timeout: 5s
      retries: 5

  keycloak:
    image: quay.io/keycloak/keycloak:26.0
    container_name: keycloak
    restart: unless-stopped
    environment:
      # Initial admin
      KC_BOOTSTRAP_ADMIN_USERNAME: admin
      KC_BOOTSTRAP_ADMIN_PASSWORD: admin
      # Database
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://keycloak-postgres:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: keycloak-dev-123
      # Settings
      KC_HOSTNAME: localhost
      KC_HTTP_ENABLED: "true"
      KC_HOSTNAME_STRICT: "false"
      KC_PROXY_HEADERS: xforwarded
      TZ: America/Sao_Paulo
    ports:
      - "8443:8443"
      - "8180:8080"
    command: start-dev
    depends_on:
      keycloak-postgres:
        condition: service_healthy

volumes:
  keycloak-pgdata:

⚠️ Warning: The start-dev command enables development mode with HTTP, local cache and theme hot-reload. Never use start-dev in production β€” use start with HTTPS configured and the proper production variables.

Start the stack:

1
docker compose -f docker-compose.keycloak.yml up -d

After a few seconds, open the admin panel at http://localhost:8180 with the credentials admin / admin.

Initial Configuration: Realm and Client

Keycloak organizes everything into Realms β€” each realm is an isolated space with its own users, clients, roles and settings. The master realm is reserved for server administration. I create a realm for the application:

1. Create a Realm

  1. In the admin panel, click the master dropdown in the top left corner
  2. Click Create Realm
  3. Fill in: Realm name = meu-app
  4. Click Create

2. Create a Client (for the ASP.NET Core API)

  1. In the meu-app realm, go to Clients β†’ Create client
  2. Fill in:
    • Client type: OpenID Connect
    • Client ID: minha-api
  3. On the next screen:
    • Client authentication: ON (confidential client)
    • Authorization: ON (if you want to use authorization services)
  4. In Valid Redirect URIs: https://localhost:5001/* and http://localhost:5000/*
  5. In Web Origins: + (allows all origins of the redirect URIs)
  6. Click Save

3. Get the Client Secret

  1. After saving, go to the Credentials tab
  2. Copy the Client secret β€” you will need it in the API configuration

4. Create a Test User

  1. Go to Users β†’ Add user
  2. Fill in:
    • Username: usuario.teste
    • Email: [email protected]
    • First Name: UsuΓ‘rio
    • Last Name: Teste
    • Email verified: ON
  3. Click Create
  4. Go to the Credentials tab β†’ Set password
  5. Set a password and uncheck Temporary

5. Create Roles

  1. Go to Realm roles β†’ Create role
  2. Create the roles: admin, user, manager
  3. Assign roles to the user: Users β†’ select the user β†’ Role mapping tab β†’ Assign role

ℹ️ Info: Everything I did manually above can be automated via the Keycloak Admin REST API or by importing a realm as JSON β€” ideal for CI/CD pipelines.

Overview of the Authentication Flow

Before diving into the code, see how the pieces fit together. The diagram below shows the complete flow: the Browser authenticates through OpenID Connect in Keycloak, receives a JWT and sends it as a Bearer Token to the ASP.NET Core API, which validates the token using Keycloak’s public keys (JWKS):

Diagram of the authentication flow between Browser, Keycloak and ASP.NET Core API in Docker containers with PostgreSQL

Integration with C# and ASP.NET Core

The following examples use C# with ASP.NET Core, but the same flow applies to any language/framework. Keycloak communicates through standard protocols (OIDC/OAuth2), so the integration comes down to configuring JWT Bearer validation in your stack β€” something every modern platform supports natively or through a library:

Language / FrameworkIntegration Library / Feature
C# / ASP.NET CoreMicrosoft.AspNetCore.Authentication.JwtBearer (used in this article)
Java / Spring BootSpring Security OAuth2 Resource Server β€” spring-boot-starter-oauth2-resource-server
Python / Djangodjango-allauth or mozilla-django-oidc
Python / FastAPIpython-jose + manual JWT validation or fastapi-keycloak
Node.js / Expresskeycloak-connect (official adapter) or jsonwebtoken + JWKS
Node.js / NestJSnest-keycloak-connect
Gogo-oidc (CoreOS)
PHP / Laravelsocialiteproviders/keycloak or robsontenorio/laravel-keycloak-guard
Ruby on Railsomniauth-keycloak
Angular / React / Vuekeycloak-js (official adapter for SPAs)

ℹ️ Info: Keycloak also offers official adapters for several platforms. However, for new integrations the recommendation is to use your language’s generic OIDC/JWT libraries β€” that way you are not coupled to a Keycloak-specific adapter.

API Configuration

I create a REST API protected by Keycloak using ASP.NET Core 8 with OpenID Connect / JWT Bearer authentication:

1
2
3
dotnet new webapi -n MinhaApi.Keycloak -f net8.0
cd MinhaApi.Keycloak
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Configure appsettings.json with the Keycloak data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "Keycloak": {
    "Authority": "http://localhost:8180/realms/meu-app",
    "Audience": "minha-api",
    "ClientId": "minha-api",
    "ClientSecret": "SEU_CLIENT_SECRET_AQUI",
    "RequireHttpsMetadata": false
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

⚠️ Warning: In production, RequireHttpsMetadata must be true and the ClientSecret must come from environment variables or Azure Key Vault, never hardcoded in appsettings.json.

Program.cs β€” Complete Configuration

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Loads the Keycloak configuration
var keycloakConfig = builder.Configuration.GetSection("Keycloak");

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = keycloakConfig["Authority"];
    options.Audience = keycloakConfig["Audience"];
    options.RequireHttpsMetadata = bool.Parse(
        keycloakConfig["RequireHttpsMetadata"] ?? "true"
    );

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = keycloakConfig["Authority"],
        ValidateAudience = true,
        ValidAudience = keycloakConfig["Audience"],
        ValidateLifetime = true,
        // Maps Keycloak roles to .NET claims
        RoleClaimType = ClaimTypes.Role,
        NameClaimType = "preferred_username"
    };

    // Extracts the realm roles from the Keycloak JWT
    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = context =>
        {
            MapKeycloakRolesToClaims(context);
            return Task.CompletedTask;
        }
    };
});

builder.Services.AddAuthorization(options =>
{
    // Policies based on Keycloak roles
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("admin"));

    options.AddPolicy("UserOrAdmin", policy =>
        policy.RequireRole("user", "admin"));

    options.AddPolicy("ManagerOnly", policy =>
        policy.RequireRole("manager"));
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

// Extracts realm_access.roles from the Keycloak JWT
// and adds them as Role claims to the ClaimsPrincipal
static void MapKeycloakRolesToClaims(TokenValidatedContext context)
{
    if (context.Principal?.Identity is not ClaimsIdentity identity)
        return;

    // Keycloak stores roles in realm_access.roles in the JWT
    var realmAccess = context.Principal.FindFirst("realm_access");
    if (realmAccess is null)
        return;

    using var doc = System.Text.Json.JsonDocument.Parse(realmAccess.Value);

    if (!doc.RootElement.TryGetProperty("roles", out var roles))
        return;

    foreach (var role in roles.EnumerateArray())
    {
        var roleName = role.GetString();
        if (!string.IsNullOrEmpty(roleName))
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, roleName));
        }
    }
}

πŸ’‘ Tip: Keycloak stores realm roles inside a claim called realm_access in the JWT. The code above extracts those roles and maps them to .NET’s ClaimTypes.Role, which lets you use [Authorize(Roles = "admin")] normally. Without this mapping, User.IsInRole("admin") does not work.

Protected Controller

Create a controller that demonstrates the different access levels:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace MinhaApi.Keycloak.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProtegidoController : ControllerBase
{
    // Public route β€” no authentication
    [HttpGet("publico")]
    [AllowAnonymous]
    public IActionResult RotaPublica()
    {
        return Ok(new { mensagem = "This route is public and requires no authentication." });
    }

    // Protected route β€” any authenticated user
    [HttpGet("autenticado")]
    [Authorize]
    public IActionResult RotaAutenticada()
    {
        var username = User.FindFirst("preferred_username")?.Value;
        var email = User.FindFirst("email")?.Value;
        var roles = User.FindAll(ClaimTypes.Role).Select(c => c.Value);

        return Ok(new
        {
            mensagem = "You are authenticated via Keycloak!",
            usuario = username,
            email,
            roles
        });
    }

    // Route restricted to admins
    [HttpGet("admin")]
    [Authorize(Policy = "AdminOnly")]
    public IActionResult RotaAdmin()
    {
        return Ok(new
        {
            mensagem = "Administrative access granted.",
            usuario = User.FindFirst("preferred_username")?.Value
        });
    }

    // Route restricted to managers
    [HttpGet("manager")]
    [Authorize(Policy = "ManagerOnly")]
    public IActionResult RotaManager()
    {
        return Ok(new
        {
            mensagem = "Manager access granted.",
            usuario = User.FindFirst("preferred_username")?.Value
        });
    }

    // Returns all claims from the JWT
    [HttpGet("claims")]
    [Authorize]
    public IActionResult VerClaims()
    {
        var claims = User.Claims.Select(c => new
        {
            tipo = c.Type,
            valor = c.Value
        });

        return Ok(claims);
    }
}

Getting a Token for Testing

To test the API, you need to get a token from Keycloak. Use the Resource Owner Password flow (for testing/development only):

1
2
3
4
5
6
7
8
curl -X POST "http://localhost:8180/realms/meu-app/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=minha-api" \
  -d "client_secret=SEU_CLIENT_SECRET" \
  -d "grant_type=password" \
  -d "username=usuario.teste" \
  -d "password=sua-senha" \
  -d "scope=openid"

The response will contain the access_token. Use it to call the API:

1
2
curl -H "Authorization: Bearer SEU_ACCESS_TOKEN" \
  http://localhost:5000/api/protegido/autenticado

Expected output:

1
2
3
4
5
6
{
  "mensagem": "You are authenticated via Keycloak!",
  "usuario": "usuario.teste",
  "email": "[email protected]",
  "roles": ["user"]
}

Service for Communicating with the Admin API

For scenarios where your application needs to manage users, roles or sessions programmatically, Keycloak exposes a complete Admin REST API. Here is how to create a service to consume this API:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace MinhaApi.Keycloak.Services;

public sealed class KeycloakAdminService
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;
    private readonly string _realm;
    private readonly string _clientId;
    private readonly string _clientSecret;

    public KeycloakAdminService(
        HttpClient httpClient,
        IConfiguration configuration)
    {
        _httpClient = httpClient;
        _baseUrl = configuration["Keycloak:Authority"]!
            .Replace($"/realms/{configuration["Keycloak:Realm"]}", "");
        _realm = configuration["Keycloak:Realm"] ?? "meu-app";
        _clientId = configuration["Keycloak:ClientId"]!;
        _clientSecret = configuration["Keycloak:ClientSecret"]!;
    }

    // Gets a service token (client credentials) to access the Admin API
    private async Task<string> GetAdminTokenAsync(
        CancellationToken cancellationToken = default)
    {
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = _clientId,
            ["client_secret"] = _clientSecret
        });

        var response = await _httpClient.PostAsync(
            $"{_baseUrl}/realms/{_realm}/protocol/openid-connect/token",
            content,
            cancellationToken);

        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync(cancellationToken);
        using var doc = JsonDocument.Parse(json);
        return doc.RootElement.GetProperty("access_token").GetString()!;
    }

    // Lists all users in the realm
    public async Task<JsonElement> ListarUsuariosAsync(
        int first = 0,
        int max = 100,
        CancellationToken cancellationToken = default)
    {
        var token = await GetAdminTokenAsync(cancellationToken);

        _httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        var response = await _httpClient.GetAsync(
            $"{_baseUrl}/admin/realms/{_realm}/users?first={first}&max={max}",
            cancellationToken);

        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync(cancellationToken);
        return JsonDocument.Parse(json).RootElement;
    }

    // Creates a new user in Keycloak
    public async Task<bool> CriarUsuarioAsync(
        string username,
        string email,
        string firstName,
        string lastName,
        string senha,
        CancellationToken cancellationToken = default)
    {
        var token = await GetAdminTokenAsync(cancellationToken);

        _httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        var novoUsuario = new
        {
            username,
            email,
            firstName,
            lastName,
            enabled = true,
            emailVerified = true,
            credentials = new[]
            {
                new
                {
                    type = "password",
                    value = senha,
                    temporary = false
                }
            }
        };

        var content = new StringContent(
            JsonSerializer.Serialize(novoUsuario),
            Encoding.UTF8,
            "application/json");

        var response = await _httpClient.PostAsync(
            $"{_baseUrl}/admin/realms/{_realm}/users",
            content,
            cancellationToken);

        return response.IsSuccessStatusCode;
    }
}

Register it in Program.cs:

1
builder.Services.AddHttpClient<KeycloakAdminService>();

ℹ️ Info: For the minha-api client to access the Admin API, you need to enable the client’s Service Account in Keycloak and assign the realm-management β†’ realm-admin role to the service account.

Implementing Logout

Logout in a Keycloak integration goes beyond simply discarding the token on the client side. For the session to be completely terminated, Keycloak must be notified so it also invalidates the session on the identity server β€” this is called RP-Initiated Logout (OpenID Connect specification).

Keycloak exposes the logout endpoint at:

1
{KEYCLOAK_URL}/realms/{REALM}/protocol/openid-connect/logout

Logout via API (Back-Channel)

To invalidate the user’s session directly from your API, use the refresh_token or the id_token_hint:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace MinhaApi.Keycloak.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;

    public AuthController(
        IConfiguration configuration,
        IHttpClientFactory httpClientFactory)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// Logs out of Keycloak by invalidating the session via back-channel.
    /// The client sends the refresh_token so Keycloak terminates the session.
    /// </summary>
    [HttpPost("logout")]
    [Authorize]
    public async Task<IActionResult> Logout(
        [FromBody] LogoutRequest request,
        CancellationToken cancellationToken = default)
    {
        var authority = _configuration["Keycloak:Authority"];
        var clientId = _configuration["Keycloak:ClientId"];
        var clientSecret = _configuration["Keycloak:ClientSecret"];

        var httpClient = _httpClientFactory.CreateClient();

        // Calls the Keycloak logout endpoint
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["client_id"] = clientId!,
            ["client_secret"] = clientSecret!,
            ["refresh_token"] = request.RefreshToken
        });

        var response = await httpClient.PostAsync(
            $"{authority}/protocol/openid-connect/logout",
            content,
            cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            var error = await response.Content.ReadAsStringAsync(cancellationToken);
            return BadRequest(new
            {
                mensagem = "Failed to log out of Keycloak.",
                detalhes = error
            });
        }

        return Ok(new { mensagem = "Logout completed successfully." });
    }

    /// <summary>
    /// Builds the Keycloak logout URL for redirection (Front-Channel).
    /// Used when the client needs to redirect the user to the Keycloak logout page.
    /// </summary>
    [HttpGet("logout-url")]
    [Authorize]
    public IActionResult GetLogoutUrl(
        [FromQuery] string? redirectUri = null)
    {
        var authority = _configuration["Keycloak:Authority"];
        var clientId = _configuration["Keycloak:ClientId"];

        var logoutUrl = $"{authority}/protocol/openid-connect/logout" +
                        $"?client_id={clientId}";

        if (!string.IsNullOrEmpty(redirectUri))
        {
            logoutUrl += $"&post_logout_redirect_uri={Uri.EscapeDataString(redirectUri)}";
        }

        return Ok(new { logoutUrl });
    }
}

public record LogoutRequest(string RefreshToken);

Register IHttpClientFactory in Program.cs (if it is not registered yet):

1
builder.Services.AddHttpClient();

Testing Logout

1. Get a token (including the refresh_token):

1
2
3
4
5
6
7
8
curl -X POST "http://localhost:8180/realms/meu-app/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=minha-api" \
  -d "client_secret=SEU_CLIENT_SECRET" \
  -d "grant_type=password" \
  -d "username=usuario.teste" \
  -d "password=sua-senha" \
  -d "scope=openid offline_access"

πŸ’‘ Tip: The offline_access scope ensures Keycloak returns a refresh_token in the response. Without it, depending on the client configuration, the refresh token may not be issued.

2. Log out via the API:

1
2
3
4
curl -X POST "http://localhost:5000/api/auth/logout" \
  -H "Authorization: Bearer SEU_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"refreshToken": "SEU_REFRESH_TOKEN"}'

3. Or get the logout URL for redirection (front-channel):

1
2
curl -H "Authorization: Bearer SEU_ACCESS_TOKEN" \
  "http://localhost:5000/api/auth/logout-url?redirectUri=http://localhost:3000"

Logout on the Front End (SPA)

For front-end applications (Angular, React, Vue), logout is usually done by redirecting to the Keycloak endpoint:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Generic example for any JavaScript framework
function logout() {
    const keycloakUrl = "http://localhost:8180";
    const realm = "meu-app";
    const clientId = "minha-api";
    const redirectUri = encodeURIComponent(window.location.origin);

    // Clears local tokens
    localStorage.removeItem("access_token");
    localStorage.removeItem("refresh_token");

    // Redirects to the Keycloak logout
    window.location.href =
        `${keycloakUrl}/realms/${realm}/protocol/openid-connect/logout` +
        `?client_id=${clientId}` +
        `&post_logout_redirect_uri=${redirectUri}`;
}

If you are using the official keycloak-js adapter, logout is even simpler:

1
2
3
4
5
6
7
8
9
// With keycloak-js
const keycloak = new Keycloak({
    url: "http://localhost:8180",
    realm: "meu-app",
    clientId: "minha-api"
});

// Logout with redirection
keycloak.logout({ redirectUri: window.location.origin });

⚠️ Warning: For post_logout_redirect_uri to work, the redirect URL must be registered in the client’s Valid Post Logout Redirect URIs in Keycloak. In development, add http://localhost:*. In production, use only the exact URLs of your domain.

Customizing the Login Page

One of Keycloak’s great advantages over cloud providers is the complete freedom to customize the login page. You can change the logo, colors, fonts and texts, and even create themes entirely from scratch using FreeMarker templates.

Structure of a Keycloak Theme

Keycloak uses a theme system based on FreeMarker Templates. Each theme can partially override the default theme (keycloak or keycloak.v2):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
themes/
└── meu-tema/
    └── login/
        β”œβ”€β”€ theme.properties          # Theme settings
        β”œβ”€β”€ resources/
        β”‚   β”œβ”€β”€ css/
        β”‚   β”‚   └── login.css         # Custom styles
        β”‚   └── img/
        β”‚       β”œβ”€β”€ logo.svg          # Custom logo
        β”‚       └── favicon.ico       # Favicon
        └── messages/
            └── messages_pt_BR.properties  # PT-BR texts

Creating the Custom Theme

1. The theme.properties file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Inherits from the default Keycloak theme and overrides only what is needed
parent=keycloak.v2
import=common/keycloak

# Custom styles
styles=css/login.css

# Overrides the logo
logo=img/logo.svg
logoUrl=https://minha-empresa.com.br

2. Custom CSS (resources/css/login.css)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* ===== Colors and Branding ===== */
:root {
    --pf-v5-global--primary-color--100: #1a73e8;    /* Primary blue */
    --pf-v5-global--primary-color--200: #1557b0;    /* Hover blue */
    --pf-v5-global--BackgroundColor--100: #f8f9fa;   /* Page background */
}

/* ===== Custom logo ===== */
.pf-v5-c-login__header .pf-v5-c-brand {
    max-height: 80px;
    width: auto;
}

/* ===== Login card ===== */
.pf-v5-c-login__main {
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
    max-width: 440px;
}

/* ===== Login button ===== */
.pf-v5-c-button.pf-m-primary {
    background-color: var(--pf-v5-global--primary-color--100);
    border-radius: 8px;
    font-weight: 600;
    padding: 12px 24px;
    transition: background-color 0.2s ease;
}

.pf-v5-c-button.pf-m-primary:hover {
    background-color: var(--pf-v5-global--primary-color--200);
}

/* ===== Input fields ===== */
.pf-v5-c-form-control {
    border-radius: 8px;
    border: 1px solid #dadce0;
    padding: 12px 16px;
}

.pf-v5-c-form-control:focus {
    border-color: var(--pf-v5-global--primary-color--100);
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

/* ===== Custom footer ===== */
.pf-v5-c-login__footer {
    text-align: center;
    font-size: 0.85rem;
    color: #5f6368;
}

/* ===== Gradient background ===== */
.pf-v5-c-login {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
}

3. Portuguese Messages (messages/messages_pt_BR.properties)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Overrides default texts for PT-BR
loginTitle=Bem-vindo de volta
loginTitleHtml=Bem-vindo de volta
doLogIn=Entrar
doRegister=Criar conta
noAccount=NΓ£o tem uma conta?
usernameOrEmail=E-mail ou nome de usuΓ‘rio
password=Senha
rememberMe=Lembrar de mim
forgotPassword=Esqueceu a senha?
backToLogin=Voltar ao login

Mounting the Theme in the Container

Add the theme volume to docker-compose.keycloak.yml:

1
2
3
4
5
6
7
8
  keycloak:
    image: quay.io/keycloak/keycloak:26.0
    # ... other settings ...
    volumes:
      - ./themes/meu-tema:/opt/keycloak/themes/meu-tema:ro
    environment:
      # ... other variables ...
      KC_SPI_THEME_DEFAULT: meu-tema

Alternatively, enable the theme from the admin panel:

  1. Go to Realm Settings β†’ Themes tab
  2. In Login theme, select meu-tema
  3. Click Save

πŸ’‘ Tip: In start-dev mode, Keycloak hot-reloads themes automatically. Just save the CSS file or the FreeMarker template and reload the login page to see the changes instantly β€” no need to restart the container.

Visual Result

After applying the theme, the login page will have:

  • βœ… Your company logo at the top
  • βœ… Custom colors on buttons and fields
  • βœ… Texts in Brazilian Portuguese
  • βœ… Login card with rounded corners and a soft shadow
  • βœ… Background with a custom gradient
  • βœ… Custom favicon

πŸ“ Example: Companies such as Red Hat, Siemens and Deutsche Telekom use Keycloak with fully customized themes that are indistinguishable from proprietary SaaS solutions. End users never notice they are using an open-source identity provider.

Keycloak in Production with Containers

Docker Compose for Production

For production, the differences from the development setup are:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# docker-compose.keycloak.prod.yml
services:
  keycloak-postgres:
    image: postgres:16-alpine
    container_name: keycloak-postgres
    restart: always
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: ${KC_DB_PASSWORD}
      TZ: America/Sao_Paulo
    volumes:
      - keycloak-pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U keycloak -d keycloak"]
      interval: 10s
      timeout: 5s
      retries: 5

  keycloak:
    image: quay.io/keycloak/keycloak:26.0
    container_name: keycloak
    restart: always
    environment:
      # Admin β€” use a strong password generated with openssl rand
      KC_BOOTSTRAP_ADMIN_USERNAME: ${KC_ADMIN_USER}
      KC_BOOTSTRAP_ADMIN_PASSWORD: ${KC_ADMIN_PASSWORD}
      # Database
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://keycloak-postgres:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: ${KC_DB_PASSWORD}
      # Production β€” HTTPS required
      KC_HOSTNAME: auth.seudominio.com.br
      KC_PROXY_HEADERS: xforwarded
      KC_HTTP_ENABLED: "false"
      KC_HTTPS_CERTIFICATE_FILE: /opt/keycloak/certs/fullchain.pem
      KC_HTTPS_CERTIFICATE_KEY_FILE: /opt/keycloak/certs/privkey.pem
      # Performance
      KC_CACHE: ispn
      KC_HEALTH_ENABLED: "true"
      KC_METRICS_ENABLED: "true"
      TZ: America/Sao_Paulo
    ports:
      - "8443:8443"
    command: start --optimized
    volumes:
      - ./certs:/opt/keycloak/certs:ro
      - ./themes/meu-tema:/opt/keycloak/themes/meu-tema:ro
    depends_on:
      keycloak-postgres:
        condition: service_healthy

volumes:
  keycloak-pgdata:

⚠️ Warning: For production, consider using build instead of volumes for the theme. The official image supports a multi-stage build with kc.sh build to optimize startup:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
FROM quay.io/keycloak/keycloak:26.0 AS builder

# Copies the custom theme
COPY themes/meu-tema /opt/keycloak/themes/meu-tema

# Optimized build with production settings
ENV KC_DB=postgres
ENV KC_CACHE=ispn
ENV KC_HEALTH_ENABLED=true
ENV KC_METRICS_ENABLED=true

RUN /opt/keycloak/bin/kc.sh build

FROM quay.io/keycloak/keycloak:26.0

COPY --from=builder /opt/keycloak/ /opt/keycloak/

ENTRYPOINT ["/opt/keycloak/bin/kc.sh"]

Production Tips β€” Security and Performance

Reverse proxy with Nginx:

If Keycloak sits behind Nginx (as in the architecture described in the BFF pattern), configure the location for reverse proxying:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
server {
    listen 443 ssl http2;
    server_name auth.seudominio.com.br;

    ssl_certificate     /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;

    location / {
        proxy_pass https://keycloak:8443;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_buffer_size 128k;
        proxy_buffers 4 256k;
        proxy_busy_buffers_size 256k;
    }
}

Tips and Good Practices

  • Keep the production realm separate from admin β€” never use the master realm for your users. Create specific realms per application or business domain.

  • Export and version the realm configuration β€” use Keycloak’s export endpoint (/admin/realms/{realm}/export) to save the configuration as JSON and version it in Git. This lets you recreate the entire environment from code (Infrastructure as Code).

  • Enable rate limiting on the reverse proxy β€” Keycloak handles authentication, a frequent target of brute-force attacks. Configure limit_req in Nginx to restrict requests to the login endpoint.

  • Configure the Infinispan cache properly β€” in production with multiple instances (cluster), Keycloak uses Infinispan for distributed session caching. See the official caching documentation for high-availability scenarios.

  • Monitor with health checks and metrics β€” enable KC_HEALTH_ENABLED and KC_METRICS_ENABLED to expose /health and /metrics endpoints (Prometheus-compatible).

  • Use start --optimized in production β€” the start command with the --optimized flag precompiles the configuration and drastically reduces startup time (from ~30s to ~5s).

  • Update regularly β€” Keycloak receives frequent security updates. Follow the official blog and test new versions in staging before updating production.

  • Back up the database regularly β€” Keycloak’s PostgreSQL holds all identity data. A scheduled pg_dump is mandatory for any production environment.

Comparison: When to Use Keycloak vs Cloud

ScenarioRecommendation
Startup with a limited budgetβœ… Keycloak β€” zero cost, all features
Company already in the Microsoft 365 ecosystem⚑ Azure Entra ID β€” native integration
100% AWS serverless application⚑ AWS Cognito β€” integration with Lambda/API Gateway
Data sovereignty requirement (LGPD, GDPR)βœ… Keycloak β€” data stays on your infrastructure
Team without infra/container experience⚑ Auth0 or Firebase Auth β€” managed SaaS
On-premises or air-gapped scenarioβœ… Keycloak β€” the only viable option
Need for full UX customizationβœ… Keycloak β€” unlimited FreeMarker themes
High scale (millions of MAU)πŸ€” It depends β€” Keycloak scales, but requires cluster expertise

ℹ️ Info: Nothing prevents a hybrid approach. Many companies use Keycloak as an identity broker federating with Azure AD/Google Workspace. Employees log in with corporate SSO (Azure AD), while session and authorization data stay centralized in Keycloak.

Conclusion

Keycloak is one of the most underrated tools in the open-source ecosystem. It delivers, for free, features that cloud providers charge hundreds or thousands of dollars a month for: SSO, MFA, identity brokering, user federation, full UI customization and a powerful REST API for automation. Running it in a container with Docker or Podman is trivial, and the OpenID Connect integration is straightforward β€” in this article I demonstrated it with ASP.NET Core and C#, but the same flow works with Java, Python, Node.js, Go, PHP, Ruby and any other technology that supports JWT and OIDC. Keycloak is a language-agnostic identity server: the authentication layer runs in the container, and your application only validates standard tokens.

If you work in a scenario where cost matters, where data sovereignty is a requirement, or you simply want full control over your application’s authentication and authorization β€” regardless of language or framework β€”, Keycloak deserves a prominent place in your stack. Start small, in a development environment with Docker Compose, validate the flow with your application, customize the login page with your brand’s visual identity and, once you are confident, promote it to production with HTTPS, a reverse proxy and backups.

Authentication is the front door of your system β€” and with Keycloak, that door is free, secure and entirely yours.

Read Also

References