ASP.NET Core: příklad OpenID Connect s PKCE

Potřebujete tři hodnoty z vývojářské konzole: ID klienta, tajný klíč klienta (jen u webových serverových aplikací) a URI přesměrování, které jste zaregistrovali. Vše ostatní je v dokumentu discovery na adrese https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Použijte vestavěný OpenID Connect handler (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 nebo novější). Zaregistrujte serverovou webovou aplikaci s URI přesměrování https://app.example.eu/signin-oidc a pro odhlášení https://app.example.eu/signout-callback-oidc. Důležitá jsou tři nastavení: Dazr vrací kód v query stringu, takže nastavte ResponseMode na query (handler výchozí používá form_post); PKCE je povinné; a ID tokeny jsou podepsané 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();

Dazr sub je User.FindFirst("sub")?.Value. Uložte ho jako klíč účtu. Client secret uchovávejte v user secrets nebo v trezoru, nikdy v appsettings.json.

Další informace pro vývojáře