I am having an issue understanding the claims, especially roles.
Following gives me two roles assigned to the user
var roles = UserManager.GetRolesAsync(user.Id).Result;
But when i get the claims and iterate through it, I only get the first role. I don't get both the roles. Please note that I haven't setup any roles in the claims at the time of login.
Action Code
IEnumerable<Claim> claims = null;
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null && identity.Claims != null && identity.Claims.Any())
{
claims = identity.Claims;
}
return View(claims);
and the corresponding view code
@model IEnumerable<System.Security.Claims.Claim>
@{
ViewBag.Title = "Display Claims";
}
<h2>Display Claims</h2>
@if (Model == null)
{
<p class="alert-danger">No claims found</p>
}
else
{
<table class="table table-bordered">
<tr>
<th>Subject</th>
<th>Issuer</th>
<th>Type</th>
<th>Value</th>
</tr>
@foreach (var claim in Model.OrderBy(x => x.Type))
{
<tr>
<td>@claim.Subject.Name</td>
<td>@claim.Issuer</td>
<td>@Html.ClaimType(claim.Type)</td>
<td>@claim.Value</td>
</tr>
}
</table>
}
and here is the output. What am I missing here?
And the table has the two roles
Update #1
I added first name and last name as remote claims, logged in and both the roles are now displaying. I didn't change any thing. So now i am more confused...
Here is the provider to add remote claims
public static class ClaimsUserInfoProvider
{
public static IEnumerable<Claim> GetClaims(ClaimsIdentity user, ApplicationUser applicationUser)
{
var claims = new List<Claim>();
claims.Add(CreateClaim(ClaimTypes.GivenName, applicationUser.FirstName + " " + applicationUser.LastName));
return claims;
}
private static Claim CreateClaim(string type, string value)
{
return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");
}
}
and the login action to use the claims provider
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Invalid user name or password.");
}
else
{
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//add claims
identity.AddClaims(ClaimsUserInfoProvider.GetClaims(identity, user));
AuthenticationManager.SignOut();
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
if (!String.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
return View(model);
}