How to implement claims-based authentication using Identity 2.0 in Asp.net MVC
asp.net, asp.net-mvc, c#, claims-based-identity, identity
Solution
Please take a look at Policies in Asp.Net Core.
In Policiy you can make use of Claims + Roles + whatever you want. All this in built in asp.net.
Here is the official reference:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies
If you're not using .Net Core you'll need a custom implementation like this authorization filter.
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
private string claimType;
private string claimValue;
public ClaimsAuthorizeAttribute(string type, string value)
{
this.claimType = type;
this.claimValue = value;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
var user = filterContext.HttpContext.User as ClaimsPrincipal;
if (user != null && user.HasClaim(claimType, claimValue))
{
base.OnAuthorization(filterContext);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Code extracted from MVC5 Claims version of the Authorize attribute
Problem
I'm working on an Asp.net Mvc application that uses identity 2 to authenticate and authorize users but it seems I need more features than Roles-based, so I want to change my method and use claims-based method to create the application. Update: Consider I want to set access permission for a specific user to access to a specific action. but the problem is there is nothing to learn, I mean i know what claim is but i don't know how to implement it and create users and things. I'm wondering why there's nothing to learn how to implement claims-based out there! that's why I asked this question. I need something like a prepared project or a step-by-step tutorial. is there anything to teach how to handle claims?