扩展 AuthorizeAttribute 覆盖 AuthorizeCore 或 OnAuthorization

发布于 2024-11-27 07:24:36 字数 142 浏览 1 评论 0原文

我使用 ASP.NET MVC 创建一个自定义 Authorize 属性来处理一些自定义授权逻辑。我看过很多例子,它非常简单,但我的问题是哪个方法最好重写,AuthorizeCore 还是 OnAuthorization?我见过很多例子,其中之一是压倒一切的。有区别吗?

Using ASP.NET MVC I am creating a custom Authorize attribute to take care of some custom authorization logic. I have looked at a lot of examples and it is pretty straight forward but my question is which method is best to override, AuthorizeCore or OnAuthorization? I have seen many examples overriding one or the other. Is there a difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

永不分离 2024-12-04 07:24:36

线索就在返回类型中:

AuthorizeCore 返回一个布尔值 - 它是决策代码。这应该仅限于查看用户的身份并测试他们所处的角色等。基本上它应该回答以下问题:

我希望该用户继续吗?

它不应该执行任何其他活动“在一边”。

OnAuthorize 返回 void - 这是您放置此时需要发生的任何功能的地方。例如写入日志、在会话中存储一些数据等。

The clue is in the return types:

AuthorizeCore returns a boolean - it is decision making code. This should be limited to looking at the user's identity and testing which roles they are in etc. etc. Basically it should answer the question:

Do I want this user to proceed?

It should not perform any additional activities "on the side".

OnAuthorize returns void - this is where you put any functionality that needs to occur at this point. e.g. Write to a log, store some data in session etc etc.

萌辣 2024-12-04 07:24:36

您应该将任何必须运行的代码放入 AuthorizeCore 中,无论用户是第一次获得授权,还是使用缓存的授权。

如果您查看源代码,您可以看到 AuthorizeCoreOnAuthorizeOnCacheAuthorization 调用。这允许缓存授权,但仍然允许某些操作并做出有关授权的实际决策。

如果您需要 AuthorizationContext 中的某些内容,则可以创建一个属性来保存该信息,然后在 AuthorizeCore 方法中访问该信息。

You should put any code that must run regardless of whether the user is being authorized for the first time, or if they are using a cached authorization in AuthorizeCore.

If you look at the source code, you can see that AuthorizeCore gets called by both OnAuthorize and OnCacheAuthorization. This allows the authorization to be cached but still allow certain actions and to make the actual decisions about the authorization.

If you need something from the AuthorizationContext then you can create a property to hold the information and then access that in the AuthorizeCore method.

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