本文介绍了MVC 3授权自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新MVC 3的用户,我试图通过SQL数据库进行管理。
首先,我有客户实体,管理员可以通过管理领域这是在客户实体布尔类型来定义。
我想打只在产品页面,而不是普通客户访问管理。
我想让[授权(角色=管理员)]而不是[授权。
但是,我不知道我怎样才能使管理角色在我的code真的。
然后在我的HomeController中,我写了这code。

I am new MVC 3 user and I am trying to make admin through SQL database.First of all, I have Customer entity and admin can be defined through admin field which is boolean type in Customer entity.I want to make to access admin only in Product page, not normal customer.And I want to make [Authorize(Roles="admin")] instead of [Authorize].However, I don't know how can I make admin role in my code really.Then in my HomeController, I written 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);
    }

和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 make 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());
    }
}

这是我的源$ C ​​$ C现在。我是否需要做AuthorizeAttribute类?
如果我必须做的,我该怎么做呢?你能不能给我解释一下?我不明白如何在我的情况下设置特定的角色。
请帮帮我,我该怎么办。谢谢你。

These are my source code now. Do I need to make 'AuthorizeAttribute' class?If I have to do, how can I make it? Could you explain to me? I cannot understand how to set particular role in my case.Please help me how can I do. Thanks.

推荐答案

您Role.IsInRole用法是不正确的。那是什么
[授权(角色=管理员)的用途,不需要调用它。

Your Role.IsInRole usage isn't correct. Thats what the[Authorize(Roles="Admin")] is used for, no need to call it.

在您的code你是不是在任何地方设置的角色。如果你想要做自定义角色的管理,你可以使用自己的角色提供或将它们存储在身份验证令牌,如下所示:

In your code you are not setting the roles anywhere. If you want to do custom role management you can use your own role provider or store them in the auth token as shown here:


注意部分:

http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorizationnote 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);
            }
        }


不过这里更简单的方法是使用内置的成员asp.net。
创建使用互联网应用模板创建一个新的MVC项目,这都将设置适合你。在Visual Studio中单击上方Solution Explorer中的asp.net配置图标。您可以在这里管理角色和分配角色。

However an easier approach here is to use the built in membership in asp.net.Create a new mvc project using the 'internet application' template and this will all be setup for you. In visual studio click on the "asp.net configuration" icon above solution explorer. You can manage roles here and assignment to roles.

这篇关于MVC 3授权自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 07:14
查看更多