关注点分离和身份验证

发布于 2024-09-04 23:44:15 字数 365 浏览 1 评论 0原文

我正在努力成为一名优秀的开发人员并消除我的担忧。我有一个包含所有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宛菡 2024-09-11 23:44:15

通常我在控制器级别处理安全性,而不是在数据级别。如果您想在数据级别处理它,那么我会使用注入为您的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文