Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ASP.NET Identity Current User In View

I use ASP.NET Identity 2.0 and MVC. I need to logged user's name,surname,email etc.. in view. How can get it? I can get just @User.Identity but there no my user class's property.

//in my view, i need here my ApplicationUser class
<div>
@User.Identity.Name
</div>

//ApplicationUser class
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim> 
{
    public ApplicationUser()
    {
        this.CreatedDate = DateTime.Now;
    }

    public DateTime CreatedDate { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }

    public string TaxOffice { get; set; }
}
like image 577
Yargicx Avatar asked Nov 26 '14 00:11

Yargicx


People also ask

How do I find HttpContext user?

HttpContext. User); Then in your DI object that needs the user you just inject IPrincipal to get the current user. The most important thing here is if you're doing unit tests you don't need to send in an HttpContext , but only need to mock something that represents IPrincipal which can just be ClaimsPrincipal .

How can get current user in ASP.NET MVC?

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .

How does HttpContext current user identity name get set?

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.

How can we get logged in user details in ASP.NET core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);


1 Answers

If there are only specific properties that you need to get, you can add them as claims in your ApplicationUser class like the following example:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    userIdentity.AddClaim(new Claim("FullName", this.FullName));
    // or use the ClaimTypes enumeration
    return userIdentity;
}

This gets wired up from the Startup.Auth class:

    SessionStateSection sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/account/login"),
        CookieName = sessionStateSection.CookieName + "_Application",
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>
                (
                     validateInterval: TimeSpan.FromMinutes(30),
                     regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                     getUserIdCallback: (id) => (id.GetUserId<int>())
                ) 

        }
    });

Then, you can access the claim (in a view or in a controller):

var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims;
var claim = claims.SingleOrDefault(m => m.Type == "FullName");

No forms authentication tickets here.

If you want the full user details available, you could always create an extension method like the following:

public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity)
{
    if (identity.IsAuthenticated)
    {
        using (var db = new AppContext())
        {
            var userManager = new ApplicationUserManager(new ApplicationUserStore(db));
            return userManager.FindByName(identity.Name);
        }
    }
    else
    {
        return null;
    }        
}

And call it like this:

@User.Identity.GetApplicationUser();

I would recommend caching if you're calling this all this time, however.

like image 144
ScottE Avatar answered Sep 20 '22 09:09

ScottE