JwtExtension.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Infrastructure;
  2. using Microsoft.AspNetCore.Authentication.JwtBearer;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.IdentityModel.Tokens;
  6. using System;
  7. using System.Threading.Tasks;
  8. namespace ZR.Infrastructure.WebExtensions
  9. {
  10. public static class JwtExtension
  11. {
  12. public static void AddJwt(this IServiceCollection services)
  13. {
  14. services.AddAuthentication(options =>
  15. {
  16. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  17. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  18. }).AddCookie()
  19. .AddJwtBearer(o =>
  20. {
  21. o.TokenValidationParameters = JwtUtil.ValidParameters();
  22. o.Events = new JwtBearerEvents
  23. {
  24. OnAuthenticationFailed = context =>
  25. {
  26. // 如果过期,把过期信息添加到头部
  27. if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
  28. {
  29. Console.WriteLine("jwt过期了");
  30. context.Response.Headers.Append("Token-Expired", "true");
  31. }
  32. return Task.CompletedTask;
  33. },
  34. };
  35. });
  36. }
  37. }
  38. }