RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to an ASP.NET Core app

Sign users in to an ASP.NET Core minimal API app with Keycloak through the OpenID Connect handler, protect an API with JwtBearer, and log out of Keycloak.

An ASP.NET Core web app signs users in with the authorization code flow and PKCE through Microsoft.AspNetCore.Authentication.OpenIdConnect, keeps the session in a cookie, and a separate ASP.NET Core API checks Keycloak access tokens with Microsoft.AspNetCore.Authentication.JwtBearer. Both use minimal APIs in Program.cs.

Written against .NET 11 (SDK 11.0.100, released 10 November 2026), the Microsoft.AspNetCore.Authentication.OpenIdConnect and Microsoft.AspNetCore.Authentication.JwtBearer packages 11.0.0, and Keycloak 26.8, checked on 25 November 2026.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

Create the client in Keycloak

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDaspnet-app
Client authenticationOn
Authentication flowStandard flow. Turn Direct access grants off.
Root URLhttps://localhost:5001
Valid redirect URIshttps://localhost:5001/signin-oidc
Valid post logout redirect URIshttps://localhost:5001/signout-callback-oidc
Web originsLeave empty. The browser never calls Keycloak from JavaScript.

Choose Save, then copy the secret from the Credentials tab.

/signin-oidc and /signout-callback-oidc are the handler's default CallbackPath and SignedOutCallbackPath. For production, add your app's real URLs next to the local ones, for example https://app.example.com/signin-oidc and https://app.example.com/signout-callback-oidc. Keycloak compares redirect URIs exactly.

Environment variables

ASP.NET Core reads configuration from environment variables, with __ between section and key. Set them in your shell, or keep the secret in dotnet user-secrets during development:

Shell
export Keycloak__Authority=https://auth.example.com/realms/acme
export Keycloak__ClientId=aspnet-app
export Keycloak__ClientSecret=paste-the-client-secret

Install

dotnet new web -o WebApp
cd WebApp
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 11.0.0
dotnet dev-certs https --trust

The handler's correlation and nonce cookies are Secure, so run the app over HTTPS with the development certificate.

Add login

Program.cs
using System.Net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

var builder = WebApplication.CreateBuilder(args);
var keycloak = builder.Configuration.GetSection("Keycloak");

builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.Authority = keycloak["Authority"];
        options.ClientId = keycloak["ClientId"];
        options.ClientSecret = keycloak["ClientSecret"];
        options.ResponseType = OpenIdConnectResponseType.Code;
        options.UsePkce = true;
        options.SaveTokens = true; // keeps the ID token for id_token_hint at sign-out
        options.MapInboundClaims = false;
        options.Scope.Add("profile");
        options.Scope.Add("email");
        options.TokenValidationParameters.NameClaimType = "preferred_username";
    });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", (HttpContext http) =>
    http.User.Identity?.IsAuthenticated == true
        ? Results.Content(
            $"<p>Signed in as {WebUtility.HtmlEncode(http.User.Identity.Name)}</p>" +
            "<form method=\"post\" action=\"/logout\"><button>Sign out</button></form>",
            "text/html")
        : Results.Content("<a href=\"/login\">Sign in</a>", "text/html"));

app.MapGet("/login", () =>
    Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }));

app.MapPost("/logout", async (HttpContext http) =>
{
    await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    await http.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme,
        new AuthenticationProperties { RedirectUri = "/" });
}).RequireAuthorization();

app.Run();

Authority is the realm's issuer; the handler reads https://auth.example.com/realms/acme/.well-known/openid-configuration from it. MapInboundClaims = false keeps Keycloak's claim names (sub, preferred_username, email) instead of the long WS-Federation names, and NameClaimType makes User.Identity.Name the username. UsePkce is on by default; it is written out here so you see it.

Run the app and sign in at https://localhost:5001:

dotnet run --urls https://localhost:5001

Since .NET 9, the handler uses pushed authorization requests (PAR) when the discovery document offers them, and Keycloak's does. The browser still goes to Keycloak's login page as usual; the request details travel from your app to Keycloak first.

Protect an API

The API is a second app on https://localhost:5002 that accepts Authorization: Bearer <access token> from other clients:

dotnet new web -o Api
cd Api
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 11.0.0

Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to the client whose tokens call the API:

  1. Open Clients, choose that client, and open its Client scopes tab.
  2. Choose <client-id>-dedicated.
  3. Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
  4. Enter a Name, set Included Custom Audience to orders-api, keep Add to access token on, and choose Save.

If your API is registered as a client in the realm, pick it under Included Client Audience instead and use its client ID as the audience.

Shell
export Keycloak__Authority=https://auth.example.com/realms/acme
export Keycloak__Audience=orders-api
Program.cs
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);
var keycloak = builder.Configuration.GetSection("Keycloak");

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = keycloak["Authority"]; // issuer and signing keys come from discovery
        options.Audience = keycloak["Audience"];
        options.MapInboundClaims = false;
        options.TokenValidationParameters.ValidateIssuer = true;
        options.TokenValidationParameters.ValidateAudience = true;
        options.TokenValidationParameters.ValidateLifetime = true;
        options.TokenValidationParameters.NameClaimType = "preferred_username";
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("admin", policy => policy.RequireAssertion(
        context => HasRealmRole(context.User, "admin")));

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api/me", (ClaimsPrincipal user) => new
{
    subject = user.FindFirstValue("sub"),
    username = user.Identity?.Name,
}).RequireAuthorization();

app.MapGet("/api/admin/ping", () => new { status = "ok" })
    .RequireAuthorization("admin");

app.Run();

// Keycloak puts realm roles in the realm_access claim: {"roles": ["admin", ...]}.
static bool HasRealmRole(ClaimsPrincipal user, string role)
{
    var realmAccess = user.FindFirstValue("realm_access");
    if (realmAccess is null) return false;
    using var doc = JsonDocument.Parse(realmAccess);
    return doc.RootElement.TryGetProperty("roles", out var roles)
        && roles.ValueKind == JsonValueKind.Array
        && roles.EnumerateArray().Any(r => r.GetString() == role);
}
dotnet run --urls https://localhost:5002

The handler checks the signature against the realm's keys from /protocol/openid-connect/certs, the issuer from the discovery document, the aud claim against Audience, and the expiry. The three Validate* lines are the defaults, written out so you see what is checked. A token without the orders-api audience, from another issuer, or with a bad signature gets a 401 with the reason in the WWW-Authenticate header; a valid token without the admin realm role gets a 403 on /api/admin/ping.

Keycloak's realm_access claim is a JSON object, so it arrives as one claim holding JSON; the admin policy reads the role list from it. Paste a token into the JWT decoder to see its iss, aud and realm_access, or list its roles with the Keycloak token roles tool.

Log out

The sign-out form posts to /logout, which calls SignOutAsync for both schemes. The cookie scheme removes the app's session. The OpenID Connect scheme sends the browser to the realm's end-session endpoint, https://auth.example.com/realms/acme/protocol/openid-connect/logout, with id_token_hint (saved because SaveTokens is on), post_logout_redirect_uri and state. Keycloak ends its own session without asking and returns to https://localhost:5001/signout-callback-oidc, which must be listed in Valid post logout redirect URIs. The handler then redirects to the RedirectUri you passed, /. The logout URL builder shows the same URL.

This logout runs through the browser, so it needs nothing from us. If you also set a Backchannel logout URL on the client, Keycloak calls your app from your tenant, and outgoing connections from your tenant are closed by default. Tell us the host and port first through How to reach us and we open the connection.

Common errors

ErrorCauseFix
IDX20803: Unable to obtain configuration from: '...'The handler cannot load the discovery document: a typo in the hostname or realm, or Keycloak__Authority is not set.Open the authority plus /.well-known/openid-configuration in a browser, or use the OIDC discovery viewer.
Keycloak shows Invalid parameter: redirect_urihttps://localhost:5001/signin-oidc is not in Valid redirect URIs, the app runs on another port, or it builds an http:// URL behind a TLS proxy.Add the URI exactly. Compare both with the redirect URI matcher, and see the proxy question below.
Correlation failed. after signing inThe correlation cookie did not come back, for example because the app runs over plain http, or you started on 127.0.0.1 and returned to localhost.Run over HTTPS on one hostname.
Sign-in fails with unauthorized_clientThe client secret is wrong, or Client authentication is off.Copy the secret again from the Credentials tab.
Keycloak shows Invalid redirect uri after Sign outhttps://localhost:5001/signout-callback-oidc is not in Valid post logout redirect URIs.Add it exactly.
API returns 401 with The audience '...' is invalid in WWW-AuthenticateThe access token has no orders-api audience.Add the Audience mapper above and get a new token. Check it with the JWT claims validator.
API returns 401 with The issuer '...' is invalidThe token comes from another realm or hostname than Authority.Get the token from the same realm, with the same hostname.
User.Identity.Name is emptyMapInboundClaims is on, or NameClaimType does not match a claim in the token.Keep MapInboundClaims = false and NameClaimType = "preferred_username".

For other OAuth error codes, see the OAuth error lookup.

FAQ

How do I check realm roles in the web app?

Keycloak's realm roles mapper adds roles to the access token only, not to the ID token the web app signs in with. Add a User Realm Role mapper to the client's dedicated scope with Add to ID token on, then use the same HasRealmRole policy as in the API.

What changes behind a reverse proxy?

When a proxy ends TLS, the app sees http:// and builds http:// redirect URIs. Add the forwarded headers middleware (app.UseForwardedHeaders() with ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto) before UseAuthentication, and configure the proxies it should trust.

Yes. With SaveTokens = true, the ID token, access token and refresh token are stored in the encrypted authentication cookie. If the cookie gets too large, keep only what you need, or store the session on the server with the cookie handler's SessionStore.

Can I use Microsoft.Identity.Web instead?

It is built for Microsoft Entra ID. For Keycloak, the plain OpenID Connect and JwtBearer handlers shown here are the simpler fit.

Sources

On this page