ASP.NET Core: ejemplo de OpenID Connect con PKCE

Necesitas tres valores de la consola para desarrolladores: el ID de cliente, el secreto de cliente (solo apps de servidor web) y la URI de redirección que registraste. Todo lo demás está en el documento de descubrimiento en https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Usa el controlador OpenID Connect integrado (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 o posterior). Registra una app de servidor web con la URI de redirección https://app.example.eu/signin-oidc y, para cerrar sesión, https://app.example.eu/signout-callback-oidc. Importan tres ajustes: Dazr devuelve el código en la query string, así que pon ResponseMode en query (el controlador usa form_post por defecto); PKCE es obligatorio; y los ID tokens se firman con 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();

El sub de Dazr es User.FindFirst("sub")?.Value. Guárdalo como clave de la cuenta. Guarda el client secret en user secrets o en un almacén de secretos, nunca en appsettings.json.

Más para desarrolladores