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

46 lines
2.1 KiB

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
namespace HuiXin.Gateway.Ocelot.Extensions
{
public static class JWTExtensions
{
public static IServiceCollection AddJWT(this IServiceCollection services, IConfiguration configuration)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(configuration.GetValue<string>("AuthenticationScheme") ?? throw new Exception("jwt的参数AuthenticationScheme未配置,请在jwt.json文件中配置"), options =>
{
//options.Authority = cfgJwt.GetValue<string>("Authority"); // OpenIddict服务端地址
//options.BackchannelTimeout = TimeSpan.FromMilliseconds(300);
options.RequireHttpsMetadata = false;
options.Audience = configuration.GetValue<string>("Audience"); // 与OpenIddict中定义的Audience匹配
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(configuration.GetValue<string>("IssuerSigningKeyBase64") ?? throw new Exception("jwt的参数IssuerSigningKeyBase64未配置,请在jwt.json文件中配置"))),
ValidateIssuer = false,
//ValidIssuer = "YOUR_ISSUER",
ValidateAudience = false,
//ValidAudience = "YOUR_AUDIENCE",
ValidateLifetime = true,
// 忽略 kid 参数
ValidateTokenReplay = false,
};
});
services.AddAuthorization();
return services;
}
public static IApplicationBuilder UseJWT(this WebApplication app)
{
app.UseAuthentication();
app.UseAuthorization();
return app;
}
}
}