优化program,jwt注入移至WebExtensions目录

This commit is contained in:
不做码农 2023-09-07 07:29:04 +08:00
parent 0fb410159a
commit 02ffc18a61
2 changed files with 42 additions and 26 deletions

View File

@ -0,0 +1,39 @@
using Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Threading.Tasks;
namespace ZR.Infrastructure.WebExtensions
{
public static class JwtExtension
{
public static void AddJwt(this IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddCookie()
.AddJwtBearer(o =>
{
o.TokenValidationParameters = JwtUtil.ValidParameters();
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;
},
};
});
}
}
}

View File

@ -1,8 +1,6 @@
using AspNetCoreRateLimit; using AspNetCoreRateLimit;
using Infrastructure.Converter; using Infrastructure.Converter;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.IdentityModel.Tokens;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Extensions;
using ZR.Common.Cache; using ZR.Common.Cache;
@ -38,31 +36,10 @@ builder.Services.AddHttpContextAccessor();
builder.Services.Configure<OptionsSetting>(builder.Configuration); builder.Services.Configure<OptionsSetting>(builder.Configuration);
//jwt 认证 //jwt 认证
builder.Services.AddAuthentication(options => builder.Services.AddJwt();
{ //配置文件
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddCookie()
.AddJwtBearer(o =>
{
o.TokenValidationParameters = JwtUtil.ValidParameters();
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;
},
};
});
builder.Services.AddSingleton(new AppSettings(builder.Configuration)); builder.Services.AddSingleton(new AppSettings(builder.Configuration));
//app服务注册
builder.Services.AddAppService(); builder.Services.AddAppService();
//开启计划任务 //开启计划任务
builder.Services.AddTaskSchedulers(); builder.Services.AddTaskSchedulers();