简体   繁体   English

现有MVC应用程序中带有Web API的AuthoriseAttribute

[英]AuthoriseAttribute with Web API in existing MVC Application

I have an existing MVC app with a custom authorize attribute overriding System.Web.Mvc.AuthorizeAttribute . 我有一个现有的MVC应用,其自定义授权属性覆盖System.Web.Mvc.AuthorizeAttribute

I now need to add Web API to the project, but only allow access to authorized users. 现在,我需要将Web API添加到项目中,但只允许访问授权用户。 If I add my custom authorize attribute to the API controller, it seems to be getting ignored and allows anyone unrestricted access. 如果我将自定义授权属性添加到API控制器,它似乎会被忽略,并允许任何人不受限制地访问。

After a bit of reading , I have found that to authorize users for Web API, you have to use System.Web.Http.AuthorizeAttribute version of the authorise attribute. 经过一番阅读后 ,我发现要授权用户使用Web API,必须使用authorize属性的System.Web.Http.AuthorizeAttribute版本。

However, after adding the Http version of the authorize attribute to my API controller, and keeping the Mvc version of the authorise attribute to my Mvc controllers, my requests to the API are now always returning 401 - Unauthorised, even when logged in. 但是,在将Authorize属性的Http版本添加到我的API控制器,并将authorize属性的Mvc版本保留到我的Mvc控制器之后,我对API的请求现在总是返回401-未经授权,即使登录也是如此。

I then tried removing my custom [Mvc] authorise attribute and use the standard version instead and got the same issue. 然后,我尝试删除我的自定义[Mvc] authorize属性,而改用标准版本,并遇到相同的问题。

This question describes a similar problem, and tries to resolve it by merging the classes from both namespaces. 此问题描述了一个类似的问题,并尝试通过合并两个命名空间中的类来解决此问题 This doesn't sound like a great solution to me, as I don't really need to customise the API authorize attribute. 对于我来说,这听起来不是一个很好的解决方案,因为我真的不需要自定义API授权属性。

What am I doing wrong here? 我在这里做错了什么?

You can only share authorization with MVC basic authentification if MVC application is in the same project as Web API. 如果MVC应用程序与Web API在同一项目中,则只能与MVC基本身份验证共享授权。 If not then you must create CustomAuthorize Attribute in Web API (inheriting http.AuthorizeAttribute) and implement basic authentification on WebAPI. 如果不是,则必须在Web API中创建CustomAuthorize Attribute(继承http.AuthorizeAttribute)并在WebAPI上实现基本身份验证。 This way every request to WebAPI should pass userName and pass in AuthHeader of HTTP Request 这样,对WebAPI的每个请求都应传递userName并传递HTTP请求的AuthHeader

I think the problem was that I was trying to call the API in server side code. 我认为问题是我试图在服务器端代码中调用API。 (Don't ask, I know it doesn't sound logical). (不要问,我知道这听起来不合逻辑)。

Obviously, the server side request would not be impersonating the users credentials. 显然,服务器端请求不会模拟用户凭据。 I tried setting <Identity Impersonate="true"/> in web.config but this had no effect. 我尝试在web.config中设置<Identity Impersonate="true"/> ,但这无效。

To work abound this issue, I have moved the request to a JQuery ajax call on document ready which I should have just done in the first place. 为了解决这个问题,我将请求移到了对文档准备就绪的JQuery ajax调用上,我应该首先完成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM