I've got a Web Forms application which I'm trying to use the new Web API beta with. The endpoints I'm exposing should only be available to an authenticated user of the site since they're for AJAX use. In my web.config I have it set to deny all users unless they're authenticated. This works as it should with Web Forms but does not work as expected with MVC or the Web API.
I've created both an MVC Controller and Web API Controller to test with. What I'm seeing is that I can't access the MVC or Web API endpoints untill I authenticate but then I can continue hitting those endpoints, even after closing my browser and recyling the app pool. But if I hit one of my aspx pages, which sends me back to my login page, then I can't hit the MVC or Web API endpoints untill I authenticate again.
Is there a reason why MVC and Web API are not functioning as my ASPX pages are once my session is invalidated? By the looks of it only the ASPX request is clearing my Forms Authentication cookie, which I'm assuming is the issue here.
Best Answer
If your web API is just used within an existing MVC application, my advice is to create a custom
AuthorizeAttribute
filter for both your MVC and WebApi controllers; I create what I call an "AuthorizeSafe" filter, which blacklists everything by default so that if you forget to apply an authorization attribute to the controller or method, you are denied access (I think the default whitelist approach is insecure).Two attribute classes are provided for you to extend;
System.Web.Mvc.AuthorizeAttribute
andSystem.Web.Http.AuthorizeAttribute
; the former is used with MVC forms authentication and the latter also hooks into forms authentication (this is very nice because it means you don't have to go building a whole separate authentication architecture for your API authentication and authorization). Here's what I came up with - it denies access to all MVC controllers/actions and WebApi controllers/actions by default unless anAllowAnonymous
orAuthorizeSafe
attribute is applied. First, an extension method to help with custom attributes:The authorization helper class that both the
AuthorizeAttribute
extensions use:The two extension classes themselves:
And finally, the attribute that can be applied to methods/controllers to allow users in certain roles to access them:
Then we register our "AuthorizeSafe" filters globally from Global.asax:
Then to open up an action to eg. anonymous access or only Admin access: