using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.IdentityModel.Tokens; using WmsLite.Api.Common; using WmsLite.Api.Infrastructure.Auth; namespace WmsLite.Api.Infrastructure; public static class AuthServiceCollectionExtensions { public static IServiceCollection AddWmsLiteAuth(this IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection(JwtOptions.SectionName)); services.AddScoped(); services.AddSingleton(); var jwt = configuration.GetSection(JwtOptions.SectionName).Get() ?? new JwtOptions(); if (string.IsNullOrWhiteSpace(jwt.Key)) { throw new InvalidOperationException( "Jwt:Key is not configured. Set Jwt:Key in user-secrets or environment variables."); } services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // 保留 JWT 原始 claim 名(sub、tenant_id 等),避免映射后 ICurrentUserContext 读不到 options.MapInboundClaims = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwt.Issuer, ValidAudience = jwt.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)), ClockSkew = TimeSpan.FromMinutes(1), }; options.Events = new JwtBearerEvents { OnChallenge = async context => { context.HandleResponse(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json; charset=utf-8"; await context.Response.WriteAsJsonAsync( BusinessResult.Fail("Unauthorized.", "401")); }, }; }); services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); }); return services; } }