如何实现自定义 RoleProvider?
我正在尝试在 ASP.NET MVC 应用程序中实现自定义 RoleProvider。
我创建了一个自定义 MembershipProvider 并且它有效,因为我能够成功验证用户。下一步是实现 RoleProvider 以将对某些控制器的访问限制为仅管理员用户。
谁能给我提供我需要采取的步骤的快速概要?
我现在的重点是我的控制器带有授权过滤器,如下所示:
[Authorize(Roles="Admin")]
public class AdminOnlyController : Controller
{
// stuff
}
并且我有我的 CustomRoleProvider 类,具有以下方法以及大量未实现的方法:
public override string[] GetRolesForUser(string username)
{
if (username == "dave")
{
return new string[] { "Admin" };
}
}
我认为我需要添加用户以某种方式到角色,但我不知道该怎么做。理想情况下,最终结果是未经授权的用户无法访问某些控制器的情况,并且我在视图中可以确定是否显示类似以下内容的链接:
if (User.IsInRole("Admin"))
{
// show links to Admin Controllers
}
任何人都可以为我指出正确的方向吗?
I'm trying to implement a custom RoleProvider in my ASP.NET MVC application.
I've created a custom MembershipProvider and it works, in that I'm able to successfully validate the user. The next step is to implement the RoleProvider to restrict access to certian Controllers to Admin users only.
Can anyone provide me with a quick outline of the steps I need to take?
The point that I'm at now is I have my controller with the Authorize filter, like so:
[Authorize(Roles="Admin")]
public class AdminOnlyController : Controller
{
// stuff
}
and I have my CustomRoleProvider class, with the following method along with a load of not-implemented Methods:
public override string[] GetRolesForUser(string username)
{
if (username == "dave")
{
return new string[] { "Admin" };
}
}
I think I need to add the user to the Role somehow but I don't know how to do that. Ideally the end result would be a scenario where unauthorized users can't access certain controllers, and I in my Views I could determine whether to show links with something like:
if (User.IsInRole("Admin"))
{
// show links to Admin Controllers
}
Can anyone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将此用作自定义角色管理器的基线:
http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx应该在 MVC 或 Web 表单中工作。
更新:由于该网页不再存在,您可以尝试 这个。基本要求是您需要实现 RoleProvider 接口,即:
I used this as as base line for a custom role manager:
http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspxShould work in MVC or Web Forms.
UPDATE: Since that web page no longer exists, you could try this one instead. The basic requirements are that you need to implement the RoleProvider interface, namely:
对于未实现的方法,请务必抛出 NotImplementedException。这应该可以帮助您确定自定义提供程序中需要哪些方法来完成工作。
我怀疑您必须实施IsUserInRole。
For the not-implemented methods, be sure to throw a NotImplementedException. This should help you figure out which methods are needed in your custom provider to get the job done.
I suspect you'll have to implement IsUserInRole.