選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JwtMiddleware.cs 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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, IUserService userService)
  13. {
  14. var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
  15. if (token != null)
  16. AttachUserToContext(context, userService, token);
  17. await _next(context);
  18. }
  19. private void AttachUserToContext(HttpContext context, 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. // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
  32. ClockSkew = TimeSpan.Zero
  33. }, out SecurityToken validatedToken);
  34. var jwtToken = (JwtSecurityToken)validatedToken;
  35. var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
  36. // attach user to context on successful jwt validation
  37. context.Items["User"] = userService.GetById(userId);
  38. }
  39. catch
  40. {
  41. // do nothing if jwt validation fails
  42. // user is not attached to context so request won't have access to secure routes
  43. }
  44. }
  45. }
  46. }