2024-03-05 19:49:58 +08:00
|
|
|
namespace Parking_space_WebAPI.Authorization;
|
2024-02-01 13:48:38 +08:00
|
|
|
|
2024-03-05 19:49:58 +08:00
|
|
|
using Parking_space_WebAPI.Services;
|
2024-02-01 13:48:38 +08:00
|
|
|
|
|
|
|
public class JwtMiddleware
|
|
|
|
{
|
|
|
|
private readonly RequestDelegate _next;
|
|
|
|
|
|
|
|
public JwtMiddleware(RequestDelegate next)
|
|
|
|
{
|
|
|
|
_next = next;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task Invoke(HttpContext context, IUserService userService, IJwtUtils jwtUtils)
|
|
|
|
{
|
|
|
|
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
|
|
|
var userId = jwtUtils.ValidateJwtToken(token);
|
|
|
|
if (userId != null)
|
|
|
|
{
|
|
|
|
// attach user to context on successful jwt validation
|
|
|
|
context.Items["User"] = userService.GetById(userId.Value);
|
|
|
|
}
|
|
|
|
var stop = "1";
|
|
|
|
await _next(context);
|
|
|
|
}
|
|
|
|
}
|