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 { /// /// 框架API授权 /// /// /// 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 => { // 可选:标记一下是否过期 if (context.Exception!=null) context.Response.Headers["Token-Expired"] = context.Exception.Message; return Task.CompletedTask; }, OnChallenge = context => { if (context.Response.Headers.ContainsKey("Token-Expired")) { } context.HandleResponse(); context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; context.Response.Headers["Access-Control-Allow-Origin"] = "*"; // ✅ 补这个 var data = new { Code = 401, Message = context.Error + context.AuthenticateFailure?.Message }; return context.Response.WriteAsync(data.ToJson()); } }; }); return services; } } }