JwtTokenUtil.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using Microsoft.IdentityModel.Tokens;
  8. namespace IMCS.CCS.Common
  9. {
  10. /// <summary>
  11. /// JWT是由 . 分割的三部分组成:
  12. /// 头部(Header)
  13. /// 载荷(Payload) : 这一部分是JWT主要的信息存储部分,其中包含了许多种的声明(claims)。
  14. /// 签名(Signature):使用保存在服务端的秘钥对其签名,用来验证发送者的JWT的同时也能确保在期间不被篡改。
  15. /// </summary>
  16. public static class JwtTokenUtil
  17. {
  18. public static string CreateToken(string id, string jwtSecurityKey, string jwtKeyName)
  19. {
  20. // push the user’s name into a claim, so we can identify the user later on.
  21. var claims = new List<Claim>();
  22. claims.Add(new Claim(ClaimTypes.Name, id));
  23. //var claims = new[]
  24. //{
  25. // new Claim(ClaimTypes.Name, Key),
  26. // //new Claim(ClaimTypes.Role, admin)//在这可以分配用户角色,比如管理员 、 vip会员 、 普通用户等
  27. //};
  28. //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
  29. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecurityKey)); // 获取密钥
  30. var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //凭证 ,根据密钥生成
  31. //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
  32. /*
  33. Claims (Payload)
  34. Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:
  35. iss: The issuer of the token,token 是给谁的 发送者
  36. aud: 接收的
  37. sub: The subject of the token,token 主题
  38. exp: Expiration Time。 token 过期时间,Unix 时间戳格式
  39. iat: Issued At。 token 创建时间, Unix 时间戳格式
  40. jti: JWT ID。针对当前 token 的唯一标识
  41. 除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
  42. */
  43. var token = new JwtSecurityToken(
  44. issuer: jwtKeyName,
  45. audience: jwtKeyName,
  46. claims: claims,
  47. expires: DateTime.Now.AddHours(12),
  48. signingCredentials: creds
  49. );
  50. return new JwtSecurityTokenHandler().WriteToken(token);
  51. }
  52. public static string ReadJwtToken(string token)
  53. {
  54. var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
  55. var readJwtToken = jwtSecurityTokenHandler.ReadJwtToken(token);
  56. var key = string.Empty;
  57. if (readJwtToken.Claims?.Count() > 0)
  58. {
  59. key = readJwtToken.Claims.FirstOrDefault()?.Value;
  60. }
  61. return key;
  62. }
  63. }
  64. }