2024-05-16 13:30:30 +08:00
|
|
|
|
using Infrastructure;
|
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
2024-07-01 16:04:10 +08:00
|
|
|
|
namespace DOAN.Infrastructure.WebExtensions
|
2024-05-16 13:30:30 +08:00
|
|
|
|
{
|
|
|
|
|
|
public static class JwtExtension
|
|
|
|
|
|
{
|
|
|
|
|
|
public static void AddJwt(this IServiceCollection services)
|
|
|
|
|
|
{
|
2024-07-22 15:12:00 +08:00
|
|
|
|
// 添加依赖 默认的身份验证方案为JWT承载
|
2024-05-16 13:30:30 +08:00
|
|
|
|
services.AddAuthentication(options =>
|
|
|
|
|
|
{
|
|
|
|
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
2024-07-22 15:12:00 +08:00
|
|
|
|
}).AddCookie() // 虽然主要使用的是JWT,.AddCookie()的调用可以为混合场景提供支持
|
|
|
|
|
|
.AddJwtBearer(o => //具体配置JWT承载身份验证
|
2024-05-16 13:30:30 +08:00
|
|
|
|
{
|
2024-07-22 15:12:00 +08:00
|
|
|
|
o.TokenValidationParameters = JwtUtil.ValidParameters(); //通常是一个包含了用于验证JWT的公钥、颁发者、接收者等信息的TokenValidationParameters对象。
|
2024-05-16 13:30:30 +08:00
|
|
|
|
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;
|
|
|
|
|
|
},
|
|
|
|
|
|
};
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|