MVC 3 Authorize Custom Roles

I am a new MVC 3 user and I am trying to do admin through an SQL database. First of all, I have a Customer and admin object, which can be defined through the admin field, which is a boolean in the Customer object. I want to make access to the administrator only on the Product page, and not in the regular client. And I want to do [Log in (Roles = "admin")] instead of [Log in]. However, I do not know how I can make the administrator role in my code. Then in my HomeController I wrote this code.

public class HomeController : Controller { [HttpPost] public ActionResult Index(Customer model) { if (ModelState.IsValid) { //define user whether admin or customer SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString()); String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'"; SqlCommand cmd = new SqlCommand(find_admin_query, conn); conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); //it defines admin which is true or false model.admin = sdr.HasRows; conn.Close(); //if admin is logged in if (model.admin == true) { Roles.IsUserInRole(model.userName, "admin"); //Is it right? if (DAL.UserIsVaild(model.userName, model.password)) { FormsAuthentication.SetAuthCookie(model.userName, true); return RedirectToAction("Index", "Product"); } } //if customer is logged in if (model.admin == false) { if (DAL.UserIsVaild(model.userName, model.password)) { FormsAuthentication.SetAuthCookie(model.userName, true); return RedirectToAction("Index", "Home"); } } ModelState.AddModelError("", "The user name or password is incorrect."); } // If we got this far, something failed, redisplay form return View(model); } 

And class DAL

  public class DAL { static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString()); public static bool UserIsVaild(string userName, string password) { bool authenticated = false; string customer_query = string.Format("SELECT * FROM [Customer] WHERE userName = '{0}' AND password = '{1}'", userName, password); SqlCommand cmd = new SqlCommand(customer_query, conn); conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); authenticated = sdr.HasRows; conn.Close(); return (authenticated); } } 

Finally, I want to do custom [Authorize (Roles = "admin")]

 [Authorize(Roles="admin")] public class ProductController : Controller { public ViewResult Index() { var product = db.Product.Include(a => a.Category); return View(product.ToList()); } } 

This is my source code. Should I use the AuthorizeAttribute class? If I have to do this, how can I do this? Could you explain to me? I cannot figure out how to establish a special role in my case. Please help me how can I do this. Thanks.

+3
source share
2 answers

Using your Role.IsInRole function is incorrect. This is what [Log in (Roles = "Admin")] is used, you do not need to call it.

You do not define a role anywhere in your code. If you want to do your own role management, you can use your own role provider or store them in an authentication token, as shown here:

http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization note the section:

 // Get the stored user-data, in this case, user roles if (!string.IsNullOrEmpty(ticket.UserData)) { string userData = ticket.UserData; string[] roles = userData.Split(','); //Roles were put in the UserData property in the authentication ticket //while creating it HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); } }

// Get the stored user-data, in this case, user roles if (!string.IsNullOrEmpty(ticket.UserData)) { string userData = ticket.UserData; string[] roles = userData.Split(','); //Roles were put in the UserData property in the authentication ticket //while creating it HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); } } 

However, a simpler approach is to use asp.net's built-in membership. Create a new mvc project using the "internet application" template and it will all be customized for you. In the visual studio, click the "asp.net configuration" icon above the solution browser. Here you can manage roles and assign roles.

+1
source

I know this question is a little old, but here's how I did something like this. I created a special authorization attribute that I used to check if the user has the correct security access:

 [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)] public sealed class AccessDeniedAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); // Get the roles from the Controller action decorated with the attribute eg // [AccessDeniedAuthorize(Roles = MyRoleEnum.UserRole + "," + MyRoleEnum.ReadOnlyRole)] var requiredRoles = Roles.Split(Convert.ToChar(",")); // Get the highest role a user has, from role provider, db lookup, etc. // (This depends on your requirements - you could also get all roles for a user and check if they have the correct access) var highestUserRole = GetHighestUserSecurityRole(); // If running locally bypass the check if (filterContext.HttpContext.Request.IsLocal) return; if (!requiredRoles.Any(highestUserRole.Contains)) { // Redirect to access denied view filterContext.Result = new ViewResult { ViewName = "AccessDenied" }; } } } 

Now decorate the Controller with a custom attribute (you can also decorate individual controller actions):

 [AccessDeniedAuthorize(Roles="user")] public class ProductController : Controller { [AccessDeniedAuthorize(Roles="admin")] public ViewResult Index() { var product = db.Product.Include(a => a.Category); return View(product.ToList()); } } 
+2
source

Source: https://habr.com/ru/post/974479/


All Articles