skip to Main Content

Is there a way to create a class in ASP.NET identity that gives me the current user who is logged into my system? I need all of his details
instead of call the User Manager each time I want to access to its details.

I am trying to make a class to give all the details of the logged in user in ASP.NET identity.

2

Answers


  1. Your question is not really clear 🙁

    Do you want to store additional user information in the ClaimsIdentity when the user logs in? That can be achieved by a class implementing the IClaimsTransformation interface. I would not recommend writing sensitive information into the claims though.

    If you want to access the user’s information, you can use the HttpContext.User. The current HttpContext can be accessed via the IHttpContextAccessor.

    Login or Signup to reply.
  2. According to your description, I suggest you could add the user infomration inside the claims instead of creating a new instance inside your application. But please notice, we don’t suggest you store the importent user information inside the claims, since the claims will be stored as cookie inside user side. By using claims, we could get more information for that user.

    More details about how to do it, you could refer to below codes:

    Crete a UserClaimsPrincipalFactory and register it inside the DI.

    public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser>
    {
        public MyUserClaimsPrincipalFactory(
            UserManager<IdentityUser> userManager,
            IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, optionsAccessor)
        {
        }
    
        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IdentityUser user)
        {
            var identity = await base.GenerateClaimsAsync(user);
            //You could store more claims into the cookie, then you could directly read the more user proerpty instead of using user manager
            identity.AddClaim(new Claim("PhoneNumber", user.PhoneNumber ?? "[11223344]"));
            return identity;
        }
    }
    

    Inside the program.cs

    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>().AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>(); 
    

    Result:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search