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.
1
2
3
4
5
6
7
8
9
10
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 );
}
}
}
copy
In my case, IUsersService is a wrapper that contains dbContext, UserManager and SignInManager.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 ;
}
}
copy
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
1
2
3
4
5
[HttpGet]
public IActionResult Index ()
{
return Json ( new { user = _httpContext . CurrentUser () });
}
copy