using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace DodoSSH.Api.Setup; /// Authentication and authorization wiring. /// /// The API validates bearer access tokens only. It never runs a browser flow itself: the desktop /// app is a public client using Authorization Code with PKCE and a loopback redirect, and it talks /// to the identity provider directly. /// internal static class Auth { /// Policy requiring an authenticated caller. internal const string AuthenticatedPolicy = "Authenticated"; /// Policy requiring a caller who has completed key enrollment. internal const string EnrolledPolicy = "Enrolled"; internal static IServiceCollection AddDodoAuthentication(this IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // Bound late so options validation has already run and the values are known good. var oidc = services.BuildServiceProvider().GetRequiredService>().Value; options.Authority = oidc.Authority; options.Audience = oidc.Audience; options.RequireHttpsMetadata = oidc.RequireHttpsMetadata; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, RequireSignedTokens = true, RequireExpirationTime = true, // 30 seconds, not the 5-minute default. A five-minute grace period on a // credential that grants vault ciphertext access is far more slack than any // sane clock needs. ClockSkew = TimeSpan.FromSeconds(30), }; // Tokens are the one thing that must never reach a log or a trace. options.IncludeErrorDetails = false; // Keep claim names as the provider issued them. The default mapping rewrites // "sub" to a long WS-Federation URI, which makes provider-agnostic claim // configuration confusing and silently breaks when a provider is swapped. options.MapInboundClaims = false; }); services.AddAuthorization(options => { options.AddPolicy(AuthenticatedPolicy, policy => policy.RequireAuthenticatedUser()); // Enrollment state lives in the database, so the real handler arrives with the // enrollment feature. Registered now so endpoint groups can reference the policy name // and the endpoint-inventory test has something to assert against. options.AddPolicy(EnrolledPolicy, policy => policy.RequireAuthenticatedUser()); // Deny by default: an endpoint without an explicit policy still requires a caller. options.FallbackPolicy = options.GetPolicy(AuthenticatedPolicy); }); return services; } }