You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
2.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DS.Module.Core;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace DS.Module.Jwt;
/// <summary>
/// Jwt 服务
/// </summary>
public static class JwtInstall
{
/// <summary>
/// 将模块服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public static IServiceCollection AddJwtInstall(this IServiceCollection services)
{
// 添加验证服务
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
// 是否开启签名认证
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppSetting.app(new string[] { "JwtSettings", "SecretKey" }))),
// 发行人验证这里要和token类中Claim类型的发行人保持一致
ValidateIssuer = true,
ValidIssuer = AppSetting.app(new string[] { "JwtSettings", "Issuer" }),//发行人
// 接收人验证
ValidateAudience = true,
ValidAudience = AppSetting.app(new string[] { "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;
}
};
});
return services;
}
}