扩展 AuthorizeAttribute 覆盖 AuthorizeCore 或 OnAuthorization
我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
线索就在返回类型中:
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.您应该将任何必须运行的代码放入
AuthorizeCore
中,无论用户是第一次获得授权,还是使用缓存的授权。如果您查看源代码,您可以看到
AuthorizeCore
被OnAuthorize
和OnCacheAuthorization
调用。这允许缓存授权,但仍然允许某些操作并做出有关授权的实际决策。如果您需要 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 bothOnAuthorize
andOnCacheAuthorization
. 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.