我自己的数据库中有一个User表,它有一个“Type”字段。有三种类型的用户,发布者,审核员和管理员。我想知道如何使用像[Authorize(Role =“Publisher”)]这样的过滤器来过滤登录的用户????
答案 0 :(得分:0)
根据我的理解,[Authorize(Role =“”)]属性在您使用角色提供程序时使用。您可以轻松自己动手 - 请参阅this链接以获取指南。
一般来说,我所拥有的是User表,Role表和UserInRole表。角色表只有一个角色ID,例如“Admin”和描述。 UserInRole表是一个连接表,用于将用户ID链接到角色ID。
这样,用户可以属于多个角色,而不仅仅与一个角色绑定。
请注意这是我的方式 - 并不一定是正确的方法。如果您想在用户表中使用“类型”字段,那么仍然可以使用 - 您的自定义角色提供程序将实现与我的不同。
编辑:此外 - [授权]属性仅适用于成员资格提供程序,并且不需要具有角色提供程序。我认为语法是[Authorize(User =“User1,User2”)]或类似的东西。
编辑:要将用户带到错误页面,表明他的角色不正确,您可以在AccountController中为Login方法添加一些自定义逻辑:
[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);
}