ASP.NET Core Identity - get current user

jbraun picture jbraun · Aug 3, 2016 · Viewed 145.7k times · Source

To get the currently logged in user in MVC5, all we had to do was:

using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
    string currentUserId = User.Identity.GetUserId();
}

Now, with ASP.NET Core I thought this should work, but it throws an error.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;

private readonly UserManager<ApplicationUser> _userManager;
[HttpPost]
[Authorize]
public async Task<IActionResult> StartSession() {
    var curUser = await _userManager.GetUserAsync(HttpContext.User);
}

Any ideas?

EDIT: Gerardo's response is on track but to get the actual "Id" of the user, this seems to work:

ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

Answer

Gerardo Grignoli picture Gerardo Grignoli · Aug 3, 2016

Assuming your code is inside an MVC controller:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

From the Controller base class, you can get the IClaimsPrincipal from the User property

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

You can check the claims directly (without a round trip to the database):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

Other fields can be fetched from the database's User entity:

  1. Get the user manager using dependency injection

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. And use it:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;