I have a MVC5 project with backend to configure which role can access which menu. The normal way to implement role based authorization is something like this.
[Authorize(Roles="Admin")]
public ActionResult UpdateProduct(ProductModel model)
{
//do something
return View(model);
}
Because I need the roles to be dynamic, I was thinking of something like this.
[Authorize(Roles=GetRoles("UpdateProduct"))]
public ActionResult UpdateProduct(ProductModel model)
{
//do something
return View(model);
}
And obviously it doesn't work because Attributes are static metadata.
I looked around and found this MVC 3 dynamic authorization of multiple roles and users but is there a cleaner way to achieve this?
Note: I'm trying to avoid calling User.IsInRole
in every method.
The definition of a code attribute in C# is that it is static - hence why you cannot have a method, GetRoles()
.
You proposed wanting an attribute such as:
[Authorize(Roles=GetRoles("UpdateProduct"))]
This would mean you would have to implement GetRoles()
in your code so use a custom attribute that is derived from Authorize
.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute(string roleSelector)
{
Roles = GetRoles(roleSelector);
}
private string GetRoles(string roleSelector)
{
// Do something to get the dynamic list of roles instead of returning a hardcoded string
return "Somerole";
}
}
So now you can do:
[CustomAuthorize("updateProduct")]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.