ASP.NET Web API 的自定义 MVC AuthorizeAttribute [英] Custom MVC AuthorizeAttribute for ASP.NET Web API

查看:26
本文介绍了ASP.NET Web API 的自定义 MVC AuthorizeAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Web API 控制器上实现自定义授权属性,但遇到了意外行为.

I am trying to implement a custom authorization attribute on my Web API controllers, but came across an unexpected behavior.

     <Authorize(Users:="myUser")>
     Public Function GetTodoItems() As IQueryable(Of TodoItem)

上面的代码工作得很好:它将允许 "myUser" 检索项目,其他任何人都不允许 bot 访问.但是,当我对自定义授权尝试相同的方法时,会跳过整个检查,任何用户都可以访问该资源.我的派生类中的 AuthorizeCoreOnAuthorization 重写方法都没有被调用.

The above code works very well: It will allow "myUser" to retrieve the items, bot nobody else is allowed access. However, when I try the same approach with my custom authorization, the entire check is skipped, and any user can access the resource. Neither the AuthorizeCore nor the OnAuthorization overridden methods in my derived class are called.

     <MyAuth(Users:="myUser")>
     Public Function GetTodoItems() As IQueryable(Of TodoItem)

派生类继承自System.Web.Mvc.AuthorizeAttribute,项目部署在IIS上,带有Windows Authentication &启用模拟,并禁用匿名身份验证.

The derived class inherits from System.Web.Mvc.AuthorizeAttribute, and the project is deployed on IIS, with Windows Authentication & Impersonation enabled, and Anonymous Authentication disabled.

如果我向 MVC 控制器添加相同的自定义授权,则它可以工作.但是在 API 控制器上,什么都没有.如果 Authorize 属性也不起作用,它会更有意义.我错过了什么吗?这是预期的行为,还是 Beta 版中的错误?

If I add the same custom authorization to an MVC Controller, then it works. But on the API Controllers, nothing. If the Authorize attribute wouldn't have worked either, it would have made more sense. Am I missing something? Is this an expected behavior, or a bug in the Beta?

推荐答案

对于 Web API,您应该使用 System.Web.Http.dll 中的 System.Web.Http.AuthorizeAttribute 而不是 System.Web.Mvc.AuthorizeAttribute.

You should use System.Web.Http.AuthorizeAttribute from System.Web.Http.dll for Web API instead of System.Web.Mvc.AuthorizeAttribute.

也就是说,因为 namespace System.Web.Http.AuthorizeAttribute 派生自 AuthorizationFilterAttribute.过滤器由 Web API 自动处理.在我自己的实现中,我直接从 AuthorizationFilterAttribute 派生而来,用于处理基本的 HTTP 身份验证.

That is, because namespace System.Web.Http.AuthorizeAttribute is derived from AuthorizationFilterAttribute. The filters are handled automatically by the Web API. In my own implementation I derived directly from AuthorizationFilterAttribute for handling of the basic HTTP authentication.

这篇关于ASP.NET Web API 的自定义 MVC AuthorizeAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆