|
|
using System.Text;
|
|
|
using DS.Module.Core;
|
|
|
using DS.Module.Core.Modules;
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
using Microsoft.AspNetCore.Builder;
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
|
namespace DS.Module.Jwt;
|
|
|
|
|
|
public class JwtModule: DSAppModule
|
|
|
{
|
|
|
public override void ConfigureServices(ConfigureServicesContext context)
|
|
|
{
|
|
|
var service = context.Services;
|
|
|
// 添加验证服务
|
|
|
service.AddAuthentication(options =>
|
|
|
{
|
|
|
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
|
}).AddJwtBearer(o =>
|
|
|
{
|
|
|
o.TokenValidationParameters = new TokenValidationParameters
|
|
|
{
|
|
|
// 是否开启签名认证
|
|
|
ValidateIssuerSigningKey = true,
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppSetting.Configuration["JwtSettings:SecretKey"])),
|
|
|
// 发行人验证,这里要和token类中Claim类型的发行人保持一致
|
|
|
ValidateIssuer = true,
|
|
|
ValidIssuer = AppSetting.Configuration["JwtSettings:Issuer"],//发行人
|
|
|
// 接收人验证
|
|
|
ValidateAudience = true,
|
|
|
ValidAudience = AppSetting.Configuration["JwtSettings:Audience"],//订阅人
|
|
|
ValidateLifetime = true,
|
|
|
ClockSkew = TimeSpan.Zero,
|
|
|
};
|
|
|
o.Events = new JwtBearerEvents
|
|
|
{
|
|
|
OnAuthenticationFailed = context =>
|
|
|
{
|
|
|
// 如果过期,则把<是否过期>添加到,返回头信息中
|
|
|
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
|
|
|
{
|
|
|
context.Response.Headers.Add("Token-Expired", "true");
|
|
|
}
|
|
|
return Task.CompletedTask;
|
|
|
}
|
|
|
};
|
|
|
});
|
|
|
}
|
|
|
|
|
|
public override void ApplicationInitialization(ApplicationContext context)
|
|
|
{
|
|
|
var app = context.GetApplicationBuilder();
|
|
|
// 先开启认证
|
|
|
app.UseAuthentication();
|
|
|
// 然后是授权中间件
|
|
|
app.UseAuthorization();
|
|
|
app.UseEndpoints(endpoints =>
|
|
|
{
|
|
|
endpoints.MapControllers();
|
|
|
});
|
|
|
}
|
|
|
} |