ASP .NET Core shared Current User

coolgoose profile image Alexandru Bucur ・1 min read

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);

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;

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

public IActionResult Index()
    return Json(new { user = _httpContext.CurrentUser() });

Posted on Aug 11 '19 by:

coolgoose profile

Alexandru Bucur


Programmer, Manager and a jack of all trades. Making things work since the dawn of time.


markdown guide