using Infrastructure; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System; using System.Threading.Tasks; namespace DOAN.Infrastructure.WebExtensions { public static class JwtExtension { public static void AddJwt(this IServiceCollection services) { // 添加依赖 默认的身份验证方案为JWT承载 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddCookie() // 虽然主要使用的是JWT,.AddCookie()的调用可以为混合场景提供支持 .AddJwtBearer(o => //具体配置JWT承载身份验证 { o.TokenValidationParameters = JwtUtil.ValidParameters(); //通常是一个包含了用于验证JWT的公钥、颁发者、接收者等信息的TokenValidationParameters对象。 o.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { // 如果过期,把过期信息添加到头部 if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { Console.WriteLine("jwt过期了"); context.Response.Headers.Add("Token-Expired", "true"); } return Task.CompletedTask; }, }; }); } } }