JWTBearer.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.IdentityModel.Tokens.Jwt;
  2. using System.Security.Claims;
  3. namespace OASystem.API.OAMethodLib.Auth
  4. {
  5. /// <summary>
  6. /// jwt
  7. /// </summary>
  8. public static class JWTBearer
  9. {
  10. public static readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
  11. public static readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();
  12. public static string GenerateToken(HttpContext httpContext)
  13. {
  14. // 请求时传入的用户参数为NameIdentifier claim的值
  15. var claims = new[] {
  16. new Claim(ClaimTypes.NameIdentifier, httpContext.Request.Query["user"])
  17. };
  18. // 签名凭据
  19. var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
  20. // 生成JWT Token
  21. var token = new JwtSecurityToken("FMGJ-OA", "OA-Users", claims, expires: DateTime.UtcNow.AddSeconds(60), signingCredentials: credentials);
  22. return JwtTokenHandler.WriteToken(token);
  23. }
  24. public static void AddMyJWTBearerAuth(this IServiceCollection services)
  25. {
  26. // 添加自定义授权
  27. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  28. .AddJwtBearer(options =>
  29. {
  30. options.TokenValidationParameters =
  31. new TokenValidationParameters
  32. {
  33. LifetimeValidator = (before, expires, token, parameters) => expires > DateTime.UtcNow,
  34. ValidateAudience = false,
  35. ValidateIssuer = false,
  36. ValidateActor = false,
  37. ValidateLifetime = true,
  38. IssuerSigningKey = JWTBearer.SecurityKey
  39. };
  40. options.Events = new JwtBearerEvents
  41. {
  42. OnMessageReceived = context =>
  43. {
  44. // 当我们收到消息时,去获取请求中的access_token字段
  45. var accessToken = context.Request.Query["access_token"];
  46. // 如果没有就去头上找,找到了就放入我们context.token中
  47. if (!string.IsNullOrEmpty(accessToken))
  48. {
  49. context.Token = accessToken;
  50. }
  51. return Task.CompletedTask;
  52. }
  53. };
  54. });
  55. }
  56. }
  57. }