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

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