Asp .Net Core 5 Identity - How to fetch a user?

545 Views Asked by At

In the new SPA (react and angular) web templates for .Net core 5. I'd like to fetch the current logged in User. However, when I try to get a user in the controller the User doesn't have anything populated.

Does anyone know how to achieve this with the new Identity Classes?

I've made a repo of the vanilla reactJS template, the only thing I changed is the line highlighted in my screenshot below to show there's no user set.

I've done a bit of googling and these pages are all I could find on the topic, unfortunately, they don't give enough detail for me to be able to implement anything practical.

enter image description here

2

There are 2 best solutions below

1
Transformer On

Backend:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
On the frontend if you need yo access it
 //with UserManager
 UserManager<ApplicationUser> UserManager
   @{
      var user = await UserManager.GetUserAsync(User);
     }

 // with SignInManager
 SignInManager<ApplicationUser> SignInManager
   @if (SignInManager.IsSignedIn(User))
0
Nicholas Bergesen On

To answer my own question.

In order to populate the User detail in the HttpContext you have 1 of 2 routes. Either change

services.AddDefaultIdentity<IdentityUser>();

to

services.AddIdentity<IdentityUser, IdentityRole>();

or you can continue to use the Core Identity

services.AddIdentityCore<IdentityUser>();

but then you also need to implement your own Microsoft.AspNetCore.Identity.ISecurityStampValidator and add it as transient services.AddTransient<ISecurityStampValidator, MyValidator>(); Your MyValidator implementation will be responsible for validating the cookie. You can see the default implementation here on github

Edit: Under the hood services.AddDefaultIdentity<IdentityUser>(); uses services.AddIdentityCore<IdentityUser>();. I feel like its importatnt to know this.