ASP.NET Core: przykład OpenID Connect z PKCE

Potrzebujesz trzech wartości z konsoli dla deweloperów: identyfikatora klienta, sekretu klienta (tylko aplikacje serwerowe) i zarejestrowanego URI przekierowania. Resztę zawiera dokument discovery pod adresem https://identity.dazr.eu/.well-known/openid-configuration.

ASP.NET Core

Użyj wbudowanej obsługi OpenID Connect (Microsoft.AspNetCore.Authentication.OpenIdConnect, .NET 8 lub nowszy). Zarejestruj aplikację serwerową z URI przekierowania https://app.example.eu/signin-oidc oraz, do wylogowania, https://app.example.eu/signout-callback-oidc. Liczą się trzy ustawienia: Dazr zwraca kod w query stringu, więc ustaw ResponseMode na query (domyślnie obsługa używa form_post); PKCE jest wymagane; a tokeny ID są podpisane 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 z Dazr to User.FindFirst("sub")?.Value. Zapisz go jako klucz konta. Trzymaj client secret w user secrets lub w sejfie, nigdy w appsettings.json.

Więcej dla deweloperów