ASP.NET Core OpenID Connect example with PKCE

You need three values from the developer console: the client ID, the client secret (web server apps only) and the redirect URI you registered. Everything else comes from the discovery document at https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Use the built-in OpenID Connect handler (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 or later). Register a web server app with the redirect URI https://app.example.eu/signin-oidc and, for sign-out, https://app.example.eu/signout-callback-oidc. Three settings matter: Dazr returns the code in the query string, so set ResponseMode to query (the handler defaults to form_post); PKCE is required; and ID tokens are signed with ES256.

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.Authority = "https://identity.dazr.eu";
    options.ClientId = builder.Configuration["Dazr:ClientId"];
    options.ClientSecret = builder.Configuration["Dazr:ClientSecret"];
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.ResponseMode = OpenIdConnectResponseMode.Query;
    options.UsePkce = true;
    options.Scope.Clear();
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.GetClaimsFromUserInfoEndpoint = true;
    options.SaveTokens = true;  // keeps the ID token for sign-out (id_token_hint)
    options.MapInboundClaims = false;  // keep sub, email and name as they are
    options.TokenValidationParameters.NameClaimType = "name";
    options.TokenValidationParameters.ValidAlgorithms = new[] { "ES256" };
});

builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/signin", () => Results.Challenge(new() { RedirectUri = "/" }));
app.MapGet("/signout", () => Results.SignOut(new() { RedirectUri = "/" },
    new[] { CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme }));
app.Run();

The Dazr sub is User.FindFirst("sub")?.Value. Store it as the account key. Keep the client secret in user secrets or a vault, never in appsettings.json.

More for developers