using System.IdentityModel.Tokens.Jwt; using Microsoft.Extensions.DependencyInjection; using System.Net; using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using VideoAnalysisCore.Common; namespace Learn.VideoAnalysis.Expand { public static class AuthorizeExpand { public static IServiceCollection AddPermissionAuthentication(this IServiceCollection services) { services.AddAuthentication() .AddJwtBearer(Authentication.vdAdmin, options => { options.RequireHttpsMetadata = false; options.UseSecurityTokenValidators = true; options.MapInboundClaims = false; // .NET 5+ JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); options.TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = false,//保存token,后台验证token是否生效(重要) RequireExpirationTime = true, // 设置请求需要携带accesstoken的过期时间 ValidateIssuer = false,//必须验证签发人 ValidateAudience = false,//验证受众 ValidateLifetime = true,//是否验证Token有效期 ValidateIssuerSigningKey = true,//是否验证签名,不验证 会被篡改数据,不安全 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppCommon.Config.AuthKey.Secret)),//解密的密钥 }; options.Events = new JwtBearerEvents { OnMessageReceived = context => { var token = context.Request.Headers["Authorization"].FirstOrDefault(); // 3. 安全提取令牌 if (!string.IsNullOrEmpty(token) && token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { // 移除"Bearer "前缀并清除两端空格 token = token.Substring("Bearer ".Length).Trim(); context.Token = token; } return Task.CompletedTask; }, OnAuthenticationFailed = context => { context.Response.StatusCode = 403; return Task.CompletedTask; }, OnChallenge = context => { context.HandleResponse(); if (context.Response.StatusCode == 403) return Task.CompletedTask; context.Response.Clear(); context.Response.ContentType = "application/json"; context.Response.StatusCode = 401; var data = new { Code = 401, Message = context.Error + context.AuthenticateFailure?.Message }; context.Response.WriteAsync(data.ToJson()); return Task.CompletedTask; } }; }); return services; } } }