JwtAuthExtension.cs 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using TEAMModelOS.SDK.Extension.JwtAuth.Models;
  2. using IdentityModel;
  3. using Microsoft.AspNetCore.Authentication.JwtBearer;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.IdentityModel.Tokens;
  8. using System;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.Context.Configuration;
  11. using TEAMModelOS.SDK.Helper.Security.RSACrypt;
  12. namespace TEAMModelOS.SDK.Extension.JwtAuth
  13. {
  14. public static class JwtAuthExtension
  15. {
  16. public static void JwtAuth(this IServiceCollection services , IConfigurationSection configuration)
  17. {
  18. services.Configure<JwtSetting>(configuration);
  19. // var creds = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"]), SecurityAlgorithms.RsaSha256Signature);
  20. //var creds = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"]));
  21. string path = BaseConfigModel.ContentRootPath;
  22. RsaSecurityKey creds = new RsaSecurityKey(RsaHelper.LoadCertificateFile(path + "/JwtRsaFile/private.pem"));
  23. //RsaSecurityKey creds = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"])), SecurityAlgorithms.RsaSha256Signature);
  24. // 令牌验证参数
  25. var tokenValidationParameters = new TokenValidationParameters
  26. {
  27. NameClaimType = JwtClaimTypes.Name,
  28. RoleClaimType = JwtClaimTypes.Role,
  29. ValidateIssuerSigningKey = true,
  30. IssuerSigningKey = creds,
  31. ValidateIssuer = true,
  32. ValidIssuer = configuration["Issuer"],//发行人
  33. ValidateAudience = true,
  34. ValidAudience = configuration["Audience"],//订阅人
  35. // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
  36. ValidateLifetime = true,
  37. //允许的服务器时间偏移量
  38. ClockSkew = TimeSpan.Zero,
  39. //是否要求Token的Claims中必须包含Expires
  40. RequireExpirationTime = true,
  41. };
  42. services.AddAuthentication(x => {
  43. x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  44. x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  45. }).AddJwtBearer(o =>
  46. {
  47. o.TokenValidationParameters = tokenValidationParameters;
  48. o.Events = new JwtBearerEvents
  49. {
  50. OnAuthenticationFailed = context =>
  51. {
  52. // 如果过期,则把<是否过期>添加到,返回头信息中
  53. if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
  54. {
  55. context.Response.Headers.Add("Token-Expired", "true");
  56. }
  57. return Task.CompletedTask;
  58. },
  59. //Url中添加access_token=[token],直接在浏览器中访问
  60. OnMessageReceived = context => {
  61. context.Token = context.Request.Query["access_token"];
  62. return Task.CompletedTask;
  63. },
  64. //URL未授权调用
  65. OnChallenge = context => {
  66. return Task.CompletedTask;
  67. },
  68. //在Token验证通过后调用
  69. OnTokenValidated = context => {
  70. //编写业务
  71. return Task.CompletedTask;
  72. },
  73. };
  74. });
  75. }
  76. }
  77. }