Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. namespace Diligent.WebAPI.Host.Middlewares
  2. {
  3. [ExcludeFromCodeCoverage]
  4. public class JwtMiddleware
  5. {
  6. private readonly RequestDelegate _next;
  7. private readonly AuthorizationSettings _authSettings;
  8. public JwtMiddleware(RequestDelegate next, IOptions<AuthorizationSettings> authSettings)
  9. {
  10. _next = next;
  11. _authSettings = authSettings.Value;
  12. }
  13. public async Task Invoke(HttpContext context, IAuthenticationService authService, IUserService userService)
  14. {
  15. var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
  16. if (token != null)
  17. await AttachUserToContext(context, authService, userService, token);
  18. await _next(context);
  19. }
  20. private async Task AttachUserToContext(HttpContext context, IAuthenticationService authService,IUserService userService, string token)
  21. {
  22. try
  23. {
  24. var tokenHandler = new JwtSecurityTokenHandler();
  25. var key = Encoding.ASCII.GetBytes(_authSettings.Secret);
  26. tokenHandler.ValidateToken(token, new TokenValidationParameters
  27. {
  28. ValidateIssuerSigningKey = true,
  29. IssuerSigningKey = new SymmetricSecurityKey(key),
  30. ValidateIssuer = false,
  31. ValidateAudience = false,
  32. RequireExpirationTime = false,
  33. ValidateLifetime = false,
  34. // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
  35. //ClockSkew = TimeSpan.Zero
  36. }, out SecurityToken validatedToken);
  37. var jwtToken = (JwtSecurityToken)validatedToken;
  38. var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
  39. // attach user to context on successful jwt validation
  40. context.Items["User"] = await userService.GetById(userId);
  41. await UpdateRefreshToken(context, authService, userId);
  42. }
  43. catch
  44. {
  45. // do nothing if jwt validation fails
  46. // user is not attached to context so request won't have access to secure routes
  47. }
  48. }
  49. private async Task UpdateRefreshToken(HttpContext context, IAuthenticationService service, int userId)
  50. {
  51. var refreshToken = await service.GetRefreshTokenByUserId(userId);
  52. if (refreshToken == null)
  53. return;
  54. if(refreshToken.ExpiryDate > DateTime.Now)
  55. {
  56. refreshToken.ExpiryDate = DateTime.Now.AddMinutes(_authSettings.JwtRefreshExpiredTime);
  57. await service.UpdateRefreshToken(refreshToken);
  58. }
  59. }
  60. }
  61. }