ASP.NET Core: exemplu OpenID Connect cu PKCE

Aveți nevoie de trei valori din consola pentru dezvoltatori: ID-ul de client, secretul de client (doar pentru aplicațiile cu server web) și URI-ul de redirecționare înregistrat. Restul se află în documentul de discovery de la https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Folosiți handlerul OpenID Connect integrat (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 sau mai nou). Înregistrați o aplicație de server web cu URI-ul de redirecționare https://app.example.eu/signin-oidc și, pentru deconectare, https://app.example.eu/signout-callback-oidc. Contează trei setări: Dazr returnează codul în query string, deci setați ResponseMode la query (handlerul folosește implicit form_post); PKCE este obligatoriu; iar tokenurile ID sunt semnate cu 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();

sub de la Dazr este User.FindFirst("sub")?.Value. Salvați-l drept cheie a contului. Păstrați client secretul în user secrets sau într-un seif, niciodată în appsettings.json.

Mai mult pentru dezvoltatori