Reputation: 139
In my ASP.NET Core MVC project, I have this scenario: a manager can do anything in the web application, you can call it super manager, and there is only one user. This "super" manager can add other managers that are more restricted, for example these managers cannot create users of type manager, or cannot see some information.
Technically, they have a lot in common. I already have many role types so I do not want to create another one called super manager where I will be creating only one user. So in this case should I use claims? or is it better to just create two roles? I know it will be less complicated but I want to know the best practice.
I'm new to ASP.NET Core so I appreciate examples or articles that could help me, thank you!
Upvotes: 0
Views: 898
Reputation: 21
I suggest if you need to create many roles, you use Claims-based authorization .
You can use Authorize[Roles = "Admin"]
property or you can create a custom AuthorizeAttribute, for example:
public class AuthorizeAccess : AuthorizeAttribute, IAuthorizationFilter
{
public string UniqueCode { get; set; }
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.User.HasClaim(c => c.Type == "CustomAccess" && c.Value.Equals(UniqueCode)))
{
// Redirect AccessDenied when the claim not exist.
context.Result = new RedirectToPageResult("/AccessDenied");
return;
}
}
}
And we can use it
[AuthorizeAccess(UniqueCode = "EDIT")]
public class IndexModel : PageModel
{
....
}
In this case you need to load a claim list in the login access
identity.AddClaim(new Claim("CustomAccess", "HOME_PAGE"));
identity.AddClaim(new Claim("CustomAccess", "EDIT"));
identity.AddClaim(new Claim("CustomAccess", "DELETE"));
identity.AddClaim(new Claim("CustomAccess", "INSERT"));
Upvotes: 1
Reputation: 27987
In my opinion, there is no difference between add the superadmin by claims or role claim, the role claim is also a type of claims.
In my opinion, if you don't have special requirement which need to add the user superadmin by claims, the best way is using claims. Since you could directly use the [Authorize(Roles = "Superadmin")]
and no need to write another codes to add the claims by using identity factory.
If you want to add the superadmin by claims, you should use UserClaimsPrincipalFactory like this answer and add the claims policy like this article shows.
Upvotes: 1