JWTExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728
  1. using Microsoft.AspNetCore.Authentication.JwtBearer;
  2. using Microsoft.AspNetCore.Authentication;
  3. using Microsoft.IdentityModel.Tokens;
  4. using System.Text;
  5. namespace DopInterfacePlatform
  6. {
  7. public static class JWTExtensions
  8. {
  9. public static AuthenticationBuilder AddJWTAuthentication(this IServiceCollection services, JwtOptions jwtOptions)
  10. {
  11. return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  12. .AddJwtBearer(x =>
  13. {
  14. x.TokenValidationParameters = new()
  15. {
  16. ValidateIssuer = true,//是否验证发行商
  17. ValidateAudience = true,//是否验证受众者
  18. ValidateLifetime = true,//是否验证失效时间
  19. ValidateIssuerSigningKey = true,//是否验证签名键
  20. ValidIssuer = jwtOptions.Issuer,
  21. ValidAudience = jwtOptions.Audience,
  22. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key))
  23. };
  24. });
  25. }
  26. }
  27. }