Reputation: 401
My User.IsInRole("CanChangeData")
is not working, but I can see in the debug menu that the Value CanChangeData
is in the claims list of the user.
I want to remove a menu if the user cannot change data in a layout, the if
return false. Request.IsAuthenticated
return true.
This is how I add the claims to the user on the AuthenticationController
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, input.Username),
},
DefaultAuthenticationTypes.ApplicationCookie,
ClaimTypes.Name, ClaimTypes.Role);
var employe = db.Employes.Single(k => k.User == input.Username);
foreach (var permission in employe.Role.Permissions)
{
identity.AddClaim(new Claim(ClaimTypes.Role, permission.Nom));
}
Why User.IsInRole("CanChangeData")
is not catching the claim ?
Upvotes: 0
Views: 442
Reputation: 37533
I use the following code to get the claims by their type:
public string GetClaimByClaimType(string claimType)
{
return ((ClaimsPrincipal) Thread.CurrentPrincipal)
.Claims
.Where(c => claimType == c.Type)
.Select(c => c.Value)
.SingleOrDefault() ?? string.Empty;
}
In your particular case, since you'd call it with:
// I would recommend using a custom claim type instead of the MS schema name
var hasCanChangeDataRole =
GetClaimByClaimType("http://schemas.microsoft.com/ws/2008/06/identity/claims/role");
var canChangeData =
"canChangeData".Equals(hasRole, StringComparison.OrdinalIgnoreCase);
Depending on your situation, you could abstract these into more concise methods. Typically I store more complex data types in the claims so my supporting methods for doing these checks is more customized.
Upvotes: 0
Reputation: 24302
You can get the associated claim values like following code,
var identity = (ClaimsIdentity) User.Identity;
var claims = identity.Claims.ToList();
if (claims.Any(x = > x.ClaimType == ClaimTypes.Role && x.ClaimValue == "CanChangeData"))
{
...
}
Upvotes: 1
Reputation: 552
When you use claims, using this as an example, you add to the claims as such:
identity.AddClaim(new Claim("ThisIsTheClaimID", "This is the value"));
Then you can use the following code to retrieve it:
var myClaimValue = User.FindFirst("ThisIsTheClaimID").Value
Hope this helps?
Upvotes: 1