JWTHelper.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using Microsoft.Extensions.Configuration;
  2. using Microsoft.IdentityModel.Tokens;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IdentityModel.Tokens;
  6. using System.IdentityModel.Tokens.Jwt;
  7. using System.Linq;
  8. using System.Security.Claims;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace SMP.Common.Auth
  12. {
  13. public static class JWTHelper
  14. {
  15. public static string CreateToken(IConfiguration configuration, UserDto user)
  16. {
  17. // 1. 定义需要使用到的Claims
  18. var claims = new[]
  19. {
  20. new Claim(ClaimTypes.Name,user.userNickName),
  21. new Claim(ClaimTypes.Role, string.Join( ',',user.roles)),
  22. new Claim(ClaimTypes.NameIdentifier,user.token)
  23. };
  24. // 2. 从 appsettings.json 中读取SecretKey
  25. var secretKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]));
  26. // 3. 选择加密算法
  27. var algorithm = SecurityAlgorithms.HmacSha256;
  28. // 4. 生成Credentials
  29. var signingCredentials = new SigningCredentials(secretKey, algorithm);
  30. // 5. 从 appsettings.json 中读取Expires
  31. var expires = Convert.ToDouble(configuration["JWT:Expires"]);
  32. // 6. 根据以上,生成token
  33. var token = new JwtSecurityToken(
  34. configuration["JWT:Issuer"], //Issuer
  35. configuration["JWT:Audience"], //Audience
  36. claims, //Claims,
  37. DateTime.Now, //notBefore
  38. DateTime.Now.AddDays(expires), //expires
  39. signingCredentials //Credentials
  40. );
  41. // 7. 将token变为string
  42. var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
  43. return jwtToken;
  44. }
  45. }
  46. }