JwtAuthExtension.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. using Microsoft.AspNetCore.Authentication.JwtBearer;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.IdentityModel.Tokens;
  6. using System;
  7. using System.Threading.Tasks;
  8. using System.Security.Claims;
  9. using System.IdentityModel.Tokens.Jwt;
  10. using System.Collections.Generic;
  11. using System.Text;
  12. namespace TEAMModelOS.SDK.Extension
  13. {
  14. public static class JwtAuthExtension
  15. {
  16. public static string CreateAuthToken(string issuer, string id,string name,string picture, string salt, string schoolID = "",string standard="", string[] roles = null, string[] permissions = null, int expire = 1)
  17. {
  18. // 設定要加入到 JWT Token 中的聲明資訊(Claims)
  19. var payload = new JwtPayload {
  20. { JwtRegisteredClaimNames.Iss, issuer }, //發行者
  21. { JwtRegisteredClaimNames.Sub, id }, // 用戶ID
  22. { JwtRegisteredClaimNames.Azp,schoolID}, // 學校簡碼,如果有的話
  23. { JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(expire).ToUnixTimeSeconds().ToString()}, // 到期的時間,必須為數字
  24. { "name",name}, // 用戶的顯示名稱
  25. { "picture",picture}, // 用戶頭像
  26. { "roles",roles}, // 登入者的角色,角色類型 (Admin、Teacher、Student)
  27. { "permissions",permissions}, //登入者的權限請求
  28. { "standard",standard} //登入者的權限請求
  29. };
  30. // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用
  31. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt));
  32. // HmacSha256 有要求必須要大於 128 bits,所以 salt 不能太短,至少要 16 字元以上
  33. // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater
  34. var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
  35. var header = new JwtHeader(signingCredentials);
  36. var secToken = new JwtSecurityToken(header, payload);
  37. // 產出所需要的 JWT securityToken 物件,並取得序列化後的 Token 結果(字串格式)
  38. var tokenHandler = new JwtSecurityTokenHandler();
  39. //var securityToken = tokenHandler.CreateToken(tokenDescriptor);
  40. var serializeToken = tokenHandler.WriteToken(secToken);
  41. return serializeToken;
  42. }
  43. public static string CreateApiToken(string issuer, string id, string salt,string name,List<int> auth , string schoolID = "", int expire = 1)
  44. {
  45. // 設定要加入到 JWT Token 中的聲明資訊(Claims)
  46. var payload = new JwtPayload {
  47. { JwtRegisteredClaimNames.Iss, issuer }, //發行者 iss: jwt签发者
  48. { JwtRegisteredClaimNames.Sub, id }, // APPID sub: jwt所面向的用户
  49. { JwtRegisteredClaimNames.Aud, "" }, // aud: 接收jwt的一方
  50. { JwtRegisteredClaimNames.Azp,schoolID}, // 學校簡碼,如果有的話
  51. {JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString() },
  52. { "name",name}, // 用戶的顯示名稱
  53. //{ JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(expire).ToUnixTimeSeconds().ToString()}, // 到期的時間,必須為數字
  54. //{ "name",name}, // 用戶的顯示名稱
  55. //{ "picture",picture}, // 用戶頭像
  56. { "auth",auth}, // 登入者的角色,角色類型 (Admin、Teacher、Student)
  57. // { "permissions",permissions} //登入者的權限請求
  58. };
  59. // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用
  60. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt));
  61. // HmacSha256 有要求必須要大於 128 bits,所以 salt 不能太短,至少要 16 字元以上
  62. // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater
  63. var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
  64. var header = new JwtHeader(signingCredentials);
  65. var secToken = new JwtSecurityToken(header, payload);
  66. // 產出所需要的 JWT securityToken 物件,並取得序列化後的 Token 結果(字串格式)
  67. var tokenHandler = new JwtSecurityTokenHandler();
  68. //var securityToken = tokenHandler.CreateToken(tokenDescriptor);
  69. var serializeToken = tokenHandler.WriteToken(secToken);
  70. return serializeToken;
  71. }
  72. public static bool ValidateApiToken(string token, string salt)
  73. {
  74. try
  75. {
  76. var handler = new JwtSecurityTokenHandler();
  77. var validationParameters = new TokenValidationParameters
  78. {
  79. RequireExpirationTime = false,
  80. ValidateIssuer = false,
  81. ValidateAudience = false,
  82. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt)),
  83. ValidateLifetime = false,
  84. //LifetimeValidator = LifetimeValidator,
  85. ClockSkew = TimeSpan.Zero
  86. };
  87. ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
  88. return true;
  89. }
  90. catch (Exception)
  91. {
  92. //Trace.WriteLine(ex.Message);
  93. return false;
  94. }
  95. }
  96. public static bool ValidateAuthToken(string token, string salt)
  97. {
  98. try
  99. {
  100. var handler = new JwtSecurityTokenHandler();
  101. var validationParameters = new TokenValidationParameters
  102. {
  103. RequireExpirationTime = true,
  104. ValidateIssuer = false,
  105. ValidateAudience = false,
  106. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt)),
  107. ValidateLifetime = false,
  108. //LifetimeValidator = LifetimeValidator,
  109. ClockSkew = TimeSpan.Zero
  110. };
  111. ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
  112. return true;
  113. }
  114. catch (Exception)
  115. {
  116. //Trace.WriteLine(ex.Message);
  117. return false;
  118. }
  119. }
  120. }
  121. }