MVC 5 Access Claims Identity User Data
Solution 1:
Try this:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
Solution 2:
You can also do this:
//Get the current claims principal
var 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);
Solution 3:
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()
Solution 4:
This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
Then you can add a base controller.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
In you controller, you would do:
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}