using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace Events.Auth; public static class AuthSetupExtensions { public static void SetupAuthenticationAndAuthorization(this IServiceCollection services, string authority, string audience) { ArgumentException.ThrowIfNullOrWhiteSpace(authority); ArgumentException.ThrowIfNullOrWhiteSpace(audience); Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddScoped(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.Authority = authority; opt.Audience = audience; opt.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidateIssuerSigningKey = true, NameClaimType = ClaimTypes.NameIdentifier }; opt.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Append("Token-Expired", "true"); } return Task.CompletedTask; } }; }); services.AddAuthorization(options => { foreach (var policy in Policies.All) { options.AddPolicy(policy.Key, policy.Value); } }); } }