using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using WebNovelPortal.Authentication; namespace Treestar.Shared.Authentication.OIDC; public static class AuthenticationExtension { public static void AddOIDCAuth(this IServiceCollection services, IConfiguration configuration) { var oidcConfig = configuration.GetRequiredSection(OpenIdConnectAuthenticationOptions.ConfigurationSection) .Get(); services.AddAuthentication(opt => { opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(opt => { opt.Authority = oidcConfig.Authority; opt.ClientId = oidcConfig.ClientId; opt.ClientSecret = oidcConfig.ClientSecret; opt.ResponseType = OpenIdConnectResponseType.Code; opt.GetClaimsFromUserInfoEndpoint = false; opt.SaveTokens = true; opt.UseTokenLifetime = true; foreach (var scope in oidcConfig.Scopes.Split(" ")) { opt.Scope.Add(scope); } opt.TokenValidationParameters = new TokenValidationParameters { NameClaimType = ClaimTypes.Name }; }); } }