Phill Greggan
Phill Greggan

Reputation: 2394

How do i set authorized access to action methods based on DB tables?

i have a mst_roles table in db with followingstructure

id  RoleName
1    Admin
2    Manager
3    Operator

the mst_users table is like this

id   username password RoleId
1     bob      123      2
2     rick     777      3

in my MVC i have a controller Orders with two action methods

public ActionResult TakeOrder()
{

}

public ActionResult StopAllTransactions()
{

}

How do i let only the Role Manager access the StopAllTransaction() and Operator has the access to TakeOrder()?

Upvotes: 0

Views: 166

Answers (1)

Deepak Kushvah
Deepak Kushvah

Reputation: 278

Action Method :

[AuthorizeDBRoleAttribute(Roles = "Role1,Role2")]
public ActionResult Welcome()
{
  return View();
}

Custom Class :

public class AuthorizeDBRoleAttribute : AuthorizeAttribute
    {
        public string Roles { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContextBase)
        {
            //Bind User Roles from Database here
            string userRoles = "Role1,Role2,Role3";

            if (userRoles.IndexOf(Roles) > -1)
                return true;
            else
                return false;
        }
}

Upvotes: 2

Related Questions