简体   繁体   中英

AuthoriseAttribute with Web API in existing MVC Application

I have an existing MVC app with a custom authorize attribute overriding System.Web.Mvc.AuthorizeAttribute .

I now need to add Web API to the project, but only allow access to authorized users. If I add my custom authorize attribute to the API controller, it seems to be getting ignored and allows anyone unrestricted access.

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.

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.

I then tried removing my custom [Mvc] authorise attribute and use the standard version instead and got the same issue.

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.

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. If not then you must create CustomAuthorize Attribute in Web API (inheriting http.AuthorizeAttribute) and implement basic authentification on WebAPI. This way every request to WebAPI should pass userName and pass in AuthHeader of HTTP Request

I think the problem was that I was trying to call the API in server side code. (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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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