jwtasp.net-core-webapiasp.net-core-5.0reactjs.net

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


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


Solution

  • 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.