JwtAuthExtension.cs 3.6 KB

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