MVC 5 Access Claims Identity User Data MVC 5 Access Claims Identity User Data asp.net asp.net

MVC 5 Access Claims Identity User Data


Try this:

[Authorize]public ActionResult SomeAction(){    var identity = (ClaimsIdentity)User.Identity;    IEnumerable<Claim> claims = identity.Claims;    ...}


You can also do this:

//Get the current claims principalvar identity = (ClaimsPrincipal)Thread.CurrentPrincipal;var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);


I make my own extended class to see what I need, so when I need into my controller or my View, I only add the using to my namespace something like this:

public static class UserExtended{    public static string GetFullName(this IPrincipal user)    {        var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.Name);        return claim == null ? null : claim.Value;    }    public static string GetAddress(this IPrincipal user)    {        var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.StreetAddress);        return claim == null ? null : claim.Value;    }    public ....    {      .....    }}

In my controller:

using XXX.CodeHelpers.Extended;var claimAddress = User.GetAddress();

In my razor:

@using DinexWebSeller.CodeHelpers.Extended;@User.GetFullName()