using Managing.Application.Abstractions.Services; namespace Managing.Api.Authorization; public class JwtMiddleware { private readonly RequestDelegate _next; public JwtMiddleware(RequestDelegate next, IConfiguration config) { _next = next; } public async Task Invoke(HttpContext context, IUserService userService, IJwtUtils jwtUtils) { if (context.Request.Path.StartsWithSegments("/User/create-token") || context.Request.Path.StartsWithSegments("/swagger") || context.Request.Path.StartsWithSegments("/health")) { await _next(context); return; } var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); if (string.IsNullOrEmpty(token)) { throw new UnauthorizedAccessException("Authorization token is missing"); } var userId = jwtUtils.ValidateJwtToken(token); if (userId != null) { // attach user to context on successful jwt validation context.Items["User"] = await userService.GetUserByAddressAsync(userId); } await _next(context); } }