DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on

ASP .NET Core shared Current User

As a quick update to the previous article explaining how to set up JWT and Identity I've updated the currentUser method to use dependency injection.

namespace Craidd.Extensions {
    public static class IHttpContextAccessorExtension
    {
        public static async Task<User> CurrentUser(this IHttpContextAccessor httpContextAccessor)
        {
            IUsersService users = httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IUsersService)) as IUsersService;
            return await users.UserManager.GetUserAsync(httpContextAccessor.HttpContext.User);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In my case, IUsersService is a wrapper that contains dbContext, UserManager and SignInManager.

namespace Craidd.Services
{
    public class UsersService: IUsersService
    {
        private readonly AppDbContext _dbContext;
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;

        public UsersService(
            AppDbContext context,
            UserManager<User> userManager,
            SignInManager<User> signInManager
        )
        {
            _dbContext = context;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public UserManager<User> UserManager => _userManager;
        public SignInManager<User> SignInManager => _signInManager;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now in your controller you can easily access the method by injecting httpContext.
I'm currently using it to quickly return the logged in user data for the Nuxt.js Auth Module

[HttpGet]
public IActionResult Index()
{
    return Json(new { user = _httpContext.CurrentUser() });
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)