开发者

How to make a RoleFilter according to my own database in MVC3

开发者 https://www.devze.com 2023-03-27 13:35 出处:网络
There is a User table in my own db and it has a \"Type\" field. There are 3 types of users, publisher, audit开发者_StackOverflow中文版ors and admins. I want to know how can i use some filter like [Aut

There is a User table in my own db and it has a "Type" field. There are 3 types of users, publisher, audit开发者_StackOverflow中文版ors and admins. I want to know how can i use some filter like [Authorize(Role="Publisher")] to filter the users logged on????


The [Authorize(Role="")] attribute, from what I understand, is used when you utilize a role provider. You can roll your own fairly easy - see this link for a guide.

Generally what I do is have a User table, Role table, and a UserInRole table. The role table just has a role id such as "Admin" and a description. The UserInRole table is a join table that links a user id to a role id.

That way a user can belong to multiple roles, and not be tied to only one.

Please note this is the way I do it - and is not necessarily the right way. If you want to use your "type" field in the user table then that will still work - your custom role provider will just be implemented different than mine.

EDIT: Also - the [Authorize] attribute will work with only a membership provider, and it is not required to have a role provider. I think the syntax is [Authorize(User="User1,User2")] or something like that.

EDIT: To take the user to an error page indicating he is not in the correct role, you could add some custom logic to your Login method in your AccountController:

[HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {

                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    if (!User.IsInRole("MyRole"))
                    {
                        return Redirect("Error");

                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }

                    }

                }
                else
                {
                    ModelState.AddModelError("", "The email or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号