ASP.NET MVC - 动态授权
我正在构建一个简单的 CMS,其中的角色在管理面板中动态设置。因此,现有的授权控制器方法的方式(例如添加[Authorize(Roles="admin")]
)已不再足够。角色-操作关系必须存储在数据库中,以便最终用户可以轻松地向管理面板中的其他人授予/获取权限。我怎样才能实现这个?
I am building a simple CMS in which roles are set dynamically in the admin panel. The existing way of authorizing a controller method, adding [Authorize(Roles="admin")]
for example, is therefore no longer sufficient. The role-action relationship must be stored in the database, so that end users can easily give/take permissions to/from others in the admin panel. How can I implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想控制授权过程,您应该子类化 AuthorizeAttribute 并覆盖 AuthorizeCore 方法。然后只需使用
CmsAuthorizeAttribute
而不是默认值来装饰您的控制器。这样做的缺点是您将无法访问 ctor 注入的 IoC,因此您必须直接从容器请求任何依赖项。
If you want to take control of the authorization process, you should subclass AuthorizeAttribute and override the AuthorizeCore method. Then simply decorate your controllers with your
CmsAuthorizeAttribute
instead of the default.The downside to this is that you won't have access to ctor-injected IoC, so you'll have to request any dependencies from the container directly.
这正是 ASP.NET 会员资格/个人资料内容为您所做的事情。它与授权属性一起使用。
如果您想推出自己的操作过滤器,您可以创建一个自定义操作过滤器来模仿标准授权操作过滤器的行为。下面的伪代码。
That is exactly what the ASP.NET membership / profile stuff does for you. And it works with the Authorize attribute.
If you want to roll your own you could create a custom action filter that mimics the behavior of the standard Authorize action filter does. Pseudo code below.
您必须在控制器方法中检查您的安全性,除非您想要子类化
AuthorizeAttribute
以便它为您从数据库中查找角色。You will have to check your security within the controller method, unless you want to subclass
AuthorizeAttribute
so that it looks up the roles from the database for you.