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;
GetCurrent(). Name; Returns: NetworkName\Username.
It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.
If your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
From the Controller
base class, you can get the ClaimsPrincipal
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:
Get the user manager using dependency injection
private UserManager<ApplicationUser> _userManager; //class constructor public MyController(UserManager<ApplicationUser> userManager) { _userManager = userManager; }
And use it:
var user = await _userManager.GetUserAsync(User); var email = user.Email;
If your code is a service class, you can use dependency injection to get an IHttpContextAccessor
that lets you get the User
from the HttpContext.
private IHttpContextAccessor _httpContextAccessor; public MyClass(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } private void DoSomething() { var user = _httpContextAccessor.Context?.User; }
If you are using Bearing Token Auth, the above samples do not return an Application User.
Instead, use this:
ClaimsPrincipal currentUser = this.User; var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value; ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
This works in apsnetcore 2.0. Have not tried in earlier versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With