You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
3.1 KiB

6 months ago
  1. using Microsoft.IdentityModel.Tokens;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Security.Claims;
  4. using System.Text;
  5. namespace Shentun.PeisReport.Api.Jwt
  6. {
  7. /// <summary>
  8. ///
  9. /// </summary>
  10. public class JwtHelper
  11. {
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. public JwtHelper()
  16. {
  17. }
  18. /// <summary>
  19. /// 获取JWT令牌
  20. /// </summary>
  21. /// <param name="claims"></param>
  22. /// <returns></returns>
  23. public string GetJwt(IEnumerable<Claim> claims)
  24. {
  25. var dateTime = DateTime.UtcNow;//世界时间
  26. //秘钥
  27. var jwtConfig = new JwtConfig();
  28. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));
  29. var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  30. // 过期时间
  31. double expMin= jwtConfig.WebExpiration;
  32. DateTime expTime = dateTime.AddMinutes(expMin);
  33. var jwt = new JwtSecurityToken(
  34. issuer: jwtConfig.Issuer,//颁发者
  35. audience: jwtConfig.Audience,//颁发给
  36. claims: claims, //声明集合
  37. notBefore: dateTime,//生效时间,这里必须使用世界时间
  38. expires: expTime,//过期时间,这里必须使用世界时间
  39. signingCredentials: creds);
  40. var jwtHandler = new JwtSecurityTokenHandler().WriteToken(jwt);
  41. return jwtHandler;
  42. }
  43. /// <summary>
  44. /// 获取TokenValidationParameters
  45. /// </summary>
  46. /// <returns></returns>
  47. public TokenValidationParameters GetTokenValidationParameters()
  48. {
  49. var jwtConfig = new JwtConfig();
  50. TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
  51. {
  52. ValidIssuer = jwtConfig.Issuer,//颁发者
  53. ValidAudience = jwtConfig.Audience,//颁发给
  54. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  55. /***********************************TokenValidationParameters的参数默认值***********************************/
  56. RequireSignedTokens = true,
  57. // SaveSigninToken = false,
  58. // ValidateActor = false,
  59. // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
  60. ValidateAudience = true,//颁发给验证
  61. ValidateIssuer = true,//颁发者验证
  62. ValidateIssuerSigningKey = true,
  63. // 是否要求Token的Claims中必须包含 Expires
  64. RequireExpirationTime = true,
  65. // 允许的服务器时间偏移量
  66. ClockSkew = TimeSpan.FromSeconds(300),
  67. // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
  68. ValidateLifetime = true
  69. };
  70. return tokenValidationParameters;
  71. }
  72. }
  73. }