关注点分离和身份验证
我正在努力成为一名优秀的开发人员并消除我的担忧。我有一个包含所有 Web 代码的 ASP.NET MVC 项目,以及一个包含所有模型代码的 DAL 项目。
有时,DAL 中的代码需要通过检查诸如 CurrentUser.IsAdmin
之类的内容来检查当前用户是否有权执行某些操作。
对于网站,当前值源自 Windows 用户名(来自 HttpContext.Current.User.Identity
),但这显然是一个 Web 问题,不应与 DAL 耦合。
松散耦合身份验证的最佳模式是什么? DAL 应该向 MVC 代码询问用户名,还是 MVC 告诉 DAL?两者之间有优点还是缺点吗?
谢谢你!
I'm trying to be a Good Developer and separate my concerns out. I've got an ASP.NET MVC project with all my web code, and a DAL project with all the model code.
Sometimes code in the DAL needs to check if the current user is authorized to perform some actions, by checking something like CurrentUser.IsAdmin
.
For the web site, the current is derived from the Windows username (from HttpContext.Current.User.Identity
), but this is clearly a web concern and shouldn't be coupled to the DAL.
What's the best pattern to loosely couple the authentication? Should the DAL be asking the MVC code for a username, or the MVC be telling the DAL? Are there advantages or disadvantages to one or the other?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常我在控制器级别处理安全性,而不是在数据级别。如果您想在数据级别处理它,那么我会使用注入为您的 DAL 提供当前用户或访问当前用户的方法。在这种情况下,这意味着在创建 DAL 实例时从控制器注入 User 对象。我有时这样做是为了审计,即当前用户可能是允许访问和修改用户数据的角色的成员。在这种情况下,我想将进行更改的实际用户插入审核表中。我会避免使用 HttpContext.Current ——您应该使用控制器上的属性并注入它们,而不是让 DAL 从静态对象中获取它们。这将使您的 DAL 更容易测试。
在控制器中处理安全性时,您可以使用 AuthorizeAttribute 或从其派生的自定义属性来实现横切安全问题。
Typically I handle the security at the controller level, not at the data level. If you want to handle it at the data level, then I'd use injection to give your DAL either the current user or the means to access who the current user is. In this case it would mean injecting the User object from the Controller when you create the DAL instance. I sometimes do this for auditing, i.e., the current user may be a member of a role that allows access to a modify a user's data. In that case I want to insert the actual user making the change into the audit table. I would avoid using HttpContext.Current -- you should use the properties on the controller instead and inject them rather than having the DAL obtain them from a static object. That will make your DAL much easier to test.
When handling security in the controller you can use the AuthorizeAttribute or custom attributes derived from it to implement your cross-cutting security concerns.