ASP.Net MVC优雅的UI和ModelBinder授权
我们知道授权的内容是一个跨领域的问题,我们会尽一切努力避免在我们的视图中合并业务逻辑。
但我仍然没有找到一种优雅的方法来使用当前用户角色过滤 UI 组件(例如小部件、表单元素、表格等),而不用业务逻辑污染视图。这同样适用于模型绑定。
示例
表单: 产品创建
字段:
- 名称、
- 价格
- 折扣
角色:
角色管理员
- 允许查看和修改“名称”字段
- 允许查看和修改价格字段
- 可以查看和修改折扣
角色管理员助理
- 可以查看和修改姓名
- 可以查看和修改价格
每个角色中显示的Fields
不同,并且模型绑定
需要忽略“管理员助理”角色的折扣字段
。
你会怎么做?
We know that authorization's stuff is a cross cutting concern, and we do anything we could to avoid merge business logic in our views.
But I still not find an elegant way to filter UI components (e.g. widgets, form elements, tables, etc) using the current user roles without contaminate the view with business logic. same applies for model binding.
Example
Form: Product Creation
Fields:
- Name
- Price
- Discount
Roles:
Role Administrator
- Is allowed to see and modify the Name field
- Is allowed to see and modify the Price field
- Is allowed to see and modify the Discount
Role Administrator assistant
- Is allowed to see and modify the Name
- Is allowed to see and modify the Price
Fields
shown in each role are different, also model binding
needs to ignore the discount field
for 'Administrator assistant' role.
How would you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为要做到这一点的方法是创建您自己的 输入扩展方法。例如,您可以创建
TextBoxRoles
并按如下方式定义它,而不是TextBox
:然后在代码中它将如下所示:
然后您的
TextBoxRoles
实现将通过 User.IsInRole() 检查当前用户的角色,以确定页面上应显示的内容。当然,您必须为您使用的每个输入扩展方法执行此操作。
On way I could think to do this is create your own versions of the input extension methods. For example instead of
TextBox
you could createTextBoxRoles
and define it like this:Then in code it would look like this:
Then your implementation of
TextBoxRoles
would check the roles of the current user viaUser.IsInRole()
to determine what should appear on the page.Of course you would have to do this for every input extension method you use.
由于您已经在控制器中拥有当前用户和对授权提供程序的访问权限,这对他们来说是理想的责任。使用简单的实现,您可以在过滤当前用户有权访问的小部件后将小部件集合传递到您的视图。就表单字段而言,当您考虑客户端验证时,事情可能会变得棘手。
绑定部分将是最直接的,针对这些特殊情况使用自定义绑定器将特别有效,因为它将可以访问控制器上下文,并且您可以从那里获取当前用户并根据以下方式绑定值您的角色定义。
Since you already have both the current user and access to the authorization provider in your controllers this is an ideal responsibility for them. Using a naive implementation you might pass a collection of widgets to your view after you filtered which widgets the current user has access to. In the case of your form field, things might get hairy when you consider client side validation.
The binding part would be the most straight forward of all, having a custom binder for these special cases will do the trick specially well since it will have access to the controller context and you can grab the current user from there and bind the values according to your role definitions.
像 LinFu 这样的 AOP 框架怎么样?如果它是横切的,那么声明它是横切的并如此对待它。
What about something like LinFu, an AOP framework? If it's crosscutting, then declare it is so and treat it as such.