JwtHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using Bowin.Common.Cache;
  2. using Bowin.Common.JSON;
  3. using Bowin.Common.Utility;
  4. using Microsoft.AspNetCore.Authentication.JwtBearer;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.SignalR;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.IdentityModel.Tokens;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IdentityModel.Tokens.Jwt;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Linq.Expressions;
  18. using System.Runtime.CompilerServices;
  19. using System.Security.Claims;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace Bowin.Common.ServiceToken
  24. {
  25. public static class JwtHelper
  26. {
  27. private static JwtSettings Settings { get; set; }
  28. private const string AUTH_SECURITY_KEY = "6bb452e82b0f6ab0253d6db9f384996552dd3afcb9113d760a00a154cabc6cbd56c5f33c246a05090005a1e8dfc148388aa6593fdbb3b5a18a73153c07a5cdd3";
  29. private const string AUTH_REFRESH_KEY = "4e64a7b3614c2710fef2fee37fe1b660302b65ca485fd57c9271e96bc36413e7c9c509a28190154b901d54abd4a45fc9b92f06fc3d798ea4b827f151f1e7c322";
  30. public static Func<string, List<string>> GetFunctionCodeMethod { get; set; }
  31. internal static Delegate GetRefreshUserFunc { get; set; }
  32. static JwtHelper()
  33. {
  34. var configuration = new ConfigurationBuilder()
  35. .SetBasePath(Directory.GetCurrentDirectory())
  36. .AddJsonFile("appsettings.json")
  37. .Build();
  38. Settings = configuration.GetSection("JwtSettings").Get<JwtSettings>();
  39. }
  40. public static void AddBowinAuthentication<T>(this IServiceCollection service, Func<string, T> refreshUserFunc, Func<string, List<string>> getFunctionGodeFunc = null)
  41. {
  42. GetRefreshUserFunc = refreshUserFunc;
  43. GetFunctionCodeMethod = getFunctionGodeFunc;
  44. service.AddAuthentication(options =>
  45. {
  46. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  47. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  48. })
  49. .AddJwtBearer(options => {
  50. options.RequireHttpsMetadata = false;
  51. options.SaveToken = true;
  52. options.TokenValidationParameters = new TokenValidationParameters
  53. {
  54. ValidateIssuer = true,
  55. ValidateAudience = true,
  56. ValidateIssuerSigningKey = true,
  57. ValidateLifetime = false,
  58. ValidAudience = Settings.Audience,
  59. ValidIssuer = Settings.Issuer,
  60. //AudienceValidator = (audiences, securityToken, validationParameters) => {
  61. // //var userID = CacheHelper.Get(securityToken.Id);
  62. // //if (userID == null)
  63. // //{
  64. // // return false;
  65. // //}
  66. // return audiences != null && audiences.FirstOrDefault().Equals(Settings.Audience);
  67. //},
  68. AudienceValidator = AudianValidator,
  69. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AUTH_SECURITY_KEY))
  70. };
  71. //options.Events = new JwtBearerEvents
  72. //{
  73. // OnTokenValidated = (context => {
  74. // //var logger = HttpHelper.GetService<ILogger<TokenSender>>();
  75. // var claims = context.Principal.Claims;
  76. // claims = claims.Where(x => x.Type != JwtRegisteredClaimNames.Aud && x.Type != JwtRegisteredClaimNames.Nbf && x.Type != JwtRegisteredClaimNames.Jti).ToArray();
  77. // var userID = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
  78. // var nowTime = DateTime.Now;
  79. // nowTime.AddMilliseconds(0 - nowTime.Millisecond);
  80. // var jti = GetJTI(userID);
  81. // claims = claims//.Append(new Claim(JwtRegisteredClaimNames.Nbf, $"{ new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds() }"))
  82. // .Append(new Claim(JwtRegisteredClaimNames.Jti, jti));
  83. // var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AUTH_SECURITY_KEY));
  84. // var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  85. // var token = new JwtSecurityToken(
  86. // issuer: Settings.Issuer,
  87. // audience: Settings.Audience,
  88. // claims: claims,
  89. // signingCredentials: creds
  90. // );
  91. // var newToken = new JwtSecurityTokenHandler().WriteToken(token);
  92. // if (jti != context.SecurityToken.Id)
  93. // {
  94. // CacheHelper.Add(jti, userID, DateTime.Now.AddDays(1));
  95. // CacheHelper.Set(context.SecurityToken.Id, userID, DateTime.Now.AddSeconds(2));
  96. // }
  97. // //context.HttpContext.Response.Headers.Add("ServiceToken", newToken);
  98. // return System.Threading.Tasks.Task.CompletedTask;
  99. // })
  100. //};
  101. });
  102. //service.AddSignalR(options => {
  103. // options.ClientTimeoutInterval = TimeSpan.FromHours(2);
  104. // options.KeepAliveInterval = TimeSpan.FromMinutes(2);
  105. //});
  106. service.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  107. var serviceProvider = service.BuildServiceProvider();
  108. HttpHelper.Accessor = serviceProvider.GetService<IHttpContextAccessor>();
  109. HttpHelper.ServiceCollection = service;
  110. HttpHelper.WebHostEnvironment = serviceProvider.GetService<IWebHostEnvironment>();
  111. }
  112. public static bool AudianValidator(IEnumerable<string> audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
  113. {
  114. var curJTI = securityToken.Id;
  115. var userID = ((JwtSecurityToken)securityToken).Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();
  116. if (string.IsNullOrEmpty(userID) || GetJTI(userID) != curJTI)
  117. {
  118. return false;
  119. }
  120. var nowId = ((JwtSecurityToken)securityToken).Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).Select(x => x.Value).FirstOrDefault();
  121. if (string.IsNullOrEmpty(nowId))
  122. {
  123. return false;
  124. }
  125. if (CacheHelper.Get(nowId) == null)
  126. {
  127. return false;
  128. }
  129. return audiences != null && audiences.FirstOrDefault().Equals(Settings.Audience);
  130. }
  131. private static string GetTimeStamp()
  132. {
  133. var nowTime = DateTime.Now;
  134. nowTime.AddMilliseconds(0 - nowTime.Millisecond);
  135. var timeStamp = new DateTimeOffset(nowTime).ToUnixTimeSeconds();
  136. return timeStamp.ToString();
  137. }
  138. private static string GetJTI(string userID)
  139. {
  140. var ip = "";//HttpHelper.GetUserIp();
  141. return (userID + ip + HttpHelper.Current.Request.Host.ToString() + ip).MD5();
  142. }
  143. public static BowinToken<T> GetToken<T>(Func<T> getUserFunc, Expression<Func<T, string>> keyExp)
  144. {
  145. var userInfo = getUserFunc.Invoke();
  146. if (userInfo == null)
  147. {
  148. throw new TokenLoginFailureException("帐号或密码错误。");
  149. }
  150. var userID = keyExp.Compile().Invoke(userInfo);
  151. var jti = GetJTI(userID.ToString());
  152. return GenerateToken(userInfo, jti, userID);
  153. }
  154. private static BowinToken<T> GenerateToken<T>(T userInfo, string jti, string userID)
  155. {
  156. var nowId = HttpHelper.Current.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
  157. var newId = Guid.NewGuid().ToString();
  158. CacheHelper.Add("uinfo_" + userID.ToString(), userInfo.ToJson());
  159. var claims = new[] {
  160. new Claim(JwtRegisteredClaimNames.Jti, jti),
  161. new Claim(JwtRegisteredClaimNames.Nbf, $"{ new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds() }"),
  162. new Claim(ClaimTypes.NameIdentifier, newId),
  163. new Claim(ClaimTypes.Name, userID.ToString())
  164. };
  165. if (GetFunctionCodeMethod != null)
  166. {
  167. CacheHelper.Add("rinfo_" + userID.ToString(), GetFunctionCodeMethod.Invoke(userID).ToJson());
  168. }
  169. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AUTH_SECURITY_KEY));
  170. var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  171. var token = new JwtSecurityToken(
  172. issuer: Settings.Issuer,
  173. audience: Settings.Audience,
  174. expires: DateTime.Now.AddMinutes(20),
  175. claims: claims,
  176. signingCredentials: creds
  177. );
  178. if (nowId != null)
  179. {
  180. CacheHelper.Set(nowId, userID, DateTime.Now.AddSeconds(30));
  181. }
  182. CacheHelper.Add(newId, userID, DateTime.Now.AddDays(1));
  183. var endToken = new BowinToken<T> { Token = new JwtSecurityTokenHandler().WriteToken(token), UserObj = userInfo };
  184. return endToken;
  185. }
  186. public static BowinToken<T> RefreshToken<T>()
  187. {
  188. var claims = HttpHelper.Current.User.Claims;
  189. var userID = claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();
  190. if (string.IsNullOrEmpty(userID))
  191. {
  192. throw new Exception("无法获取用户信息,请检查访问令牌是否错误。");
  193. }
  194. var jti = GetJTI(userID);
  195. var userInfo = JwtUser<T>.Current;
  196. if (userInfo == null)
  197. {
  198. throw new Exception("无法获取用户信息,请检查访问令牌是否错误。");
  199. }
  200. return GenerateToken(userInfo, jti, userID);
  201. }
  202. }
  203. public class TokenSender : Hub
  204. {
  205. public override async Task OnConnectedAsync()
  206. {
  207. await Groups.AddToGroupAsync(Context.ConnectionId, this.Context.GetHttpContext().Request.Query["UserID"]);
  208. }
  209. }
  210. public class TokenLoginFailureException : Exception
  211. {
  212. public TokenLoginFailureException(string message) : base(message)
  213. {
  214. }
  215. }
  216. public class JwtRereshTokenInvalidException : Exception
  217. {
  218. public JwtRereshTokenInvalidException(string message) : base(message)
  219. {
  220. }
  221. }
  222. }