feat: jwt验证

main
NoahLan 8 months ago
parent e9fee0d664
commit df1a857f16

@ -1,7 +1,9 @@
using System.Globalization;
using System.Text;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Cors;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using NPin.Application;
@ -13,6 +15,8 @@ using NPin.Framework.AspNetCore.Microsoft.AspNetCore.Builder;
using NPin.Framework.AspNetCore.Microsoft.Extensions.DependencyInjection;
using NPin.Framework.TenantManagement.Application;
using NPin.Framework.Upms.Application;
using NPin.Framework.Upms.Domain.Shared.Consts;
using NPin.Framework.Upms.Domain.Shared.Options;
using NPin.SqlSugarCore;
using Volo.Abp.AspNetCore.Authentication.JwtBearer;
using Volo.Abp.AspNetCore.MultiTenancy;
@ -169,11 +173,70 @@ public class NPinWebModule : AbpModule
});
// 配置 JWT 鉴权
// var jwtOptions = configuration.GetSection(nameof(JwtOptions))
var jwtOptions = configuration.GetSection(nameof(JwtOptions)).Get<JwtOptions>();
var refreshJwtOptions = configuration.GetSection(nameof(RefreshJwtOptions)).Get<RefreshJwtOptions>();
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddJwtBearer(opt => { })
// .AddJwtBearer(opt => { })
// access_token
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.Zero,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey))
};
opt.Events = new JwtBearerEvents
{
OnMessageReceived = ctx =>
{
var accessToken = ctx.Request.Headers["access_token"];
if (string.IsNullOrEmpty(accessToken))
{
accessToken = ctx.Request.Query["access_token"];
}
if (!string.IsNullOrEmpty(accessToken))
{
ctx.Token = accessToken;
}
return Task.CompletedTask;
}
};
})
// refresh_token
.AddJwtBearer(TokenTypeConst.Refresh, opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.Zero,
ValidateIssuerSigningKey = true,
ValidIssuer = refreshJwtOptions.Issuer,
ValidAudience = refreshJwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshJwtOptions.SecurityKey))
};
opt.Events = new JwtBearerEvents
{
OnMessageReceived = ctx =>
{
var refreshToken = ctx.Request.Headers["refresh_token"];
if (string.IsNullOrEmpty(refreshToken))
{
refreshToken = ctx.Request.Query["refresh_token"];
}
if (!string.IsNullOrEmpty(refreshToken))
{
ctx.Token = refreshToken;
}
return Task.CompletedTask;
}
};
})
.AddQQ(opt => { configuration.GetSection("OAuth:QQ").Bind(opt); })
.AddGitee(opt => { configuration.GetSection("OAuth:Gitee").Bind(opt); });

Loading…
Cancel
Save