Authorize attribute Roles from Database

952 Views Asked by At

I want to get the below roles(Admin,IT,..) from the database without hard coding on top of the action result. Please provide any help.

[Authorize(Roles = "Admin,IT")]
public ActionResult Index()
{
}
3

There are 3 best solutions below

0
ste-fu On

There aren't any super-easy ways to do this. You can apply the [Authorize] attribute to a controller instead of an action, but it is still "hard-coding" it.

You could create a custom Authorization attribute ([link])1, but you would have to store the Routing values in the database, as well as the Roles that were allowed to access the route. However this just shifts the burden of making manual changes into the database from the code.

I don't really think that this should really be considered "Hard Coding" as you have to declare your authorization somewhere, and you can still have different users with different permissions in different environments. Who else but the developer should know best which routes require which authorization? Would you want to break your access control because you changed the routing somewhere?

0
it dũng On

create an Action finter

    public class ValidationPermission : ActionFilterAttribute
    {
     public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         if(System.Web.HttpContext.Current.Session["UserName"] == null)
         System.Web.HttpContext.Current.Response.RedirectToRoute("Login");
         else{
         // code check CheckPermission
             }
        }
    }

Action controller

[ValidationPermission(Action = ActionEnum.Read, Module = CModule)]
public ActionResult Index()
 {
 // something code 
 }
0
rykamol On

You can try with this way

  public static Role {
    public static string Admin ="Admin";
    public static string IT ="IT";
  }


 [Authorize(Roles = Role.Admin,Role.IT)]
 public ActionResult Index()
 {

 }