ASP.NET Core: exemplo de OpenID Connect com PKCE

Precisa de três valores da consola para programadores: o ID de cliente, o segredo de cliente (apenas aplicações de servidor web) e o URI de redirecionamento que registou. O resto está no documento de descoberta em https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Use o handler OpenID Connect integrado (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 ou posterior). Registe uma aplicação de servidor web com o URI de redirecionamento https://app.example.eu/signin-oidc e, para terminar sessão, https://app.example.eu/signout-callback-oidc. Três definições contam: a Dazr devolve o código na query string, por isso defina ResponseMode como query (o handler usa form_post por predefinição); o PKCE é obrigatório; e os ID tokens são assinados com 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();

O sub da Dazr é User.FindFirst("sub")?.Value. Guarde-o como chave da conta. Mantenha o client secret nos user secrets ou num cofre, nunca em appsettings.json.

Mais para programadores