Newer
Older
hypermedia-blazorcrud / Blazorcrud.Server / Authorization / JwtMiddleware.cs
@Derek Comartin Derek Comartin on 12 Jul 723 bytes Init
namespace Blazorcrud.Server.Authorization;
using Blazorcrud.Server.Models;

public class JwtMiddleware
{
    private readonly RequestDelegate _next;

    public JwtMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, IUserRepository userRepository, IJwtUtils jwtUtils)
    {
        var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
        var userId = jwtUtils.ValidateToken(token);
        if (userId != null)
        {
            // attach user to context on successful jwt validation
            context.Items["User"] = await userRepository.GetUser(userId.Value);
        }

        await _next(context);
    }
}