问题
I'm working with webApi and trying to implement forms auth. My application is using simpleMembership. For some reason my controllers are reverting to my windows credentials to check and see if a request is authenticated, when it should just be using simpleMembership against my app's database:
I've disabled windows and anonymous auth in the app and in my applicationhost config file... what else needs to be done?
回答1:
In your API Controllers, when you need to enforce authentication (non-public controllers or actions) you need to use the
[Authorize]
... attribute at either the controllers or action level, according to your needs. Please note this is the attribute implemented on System.Web.Http not the one in System.Web.Mvc
The one you use for Api Controllers checks the Thread.CurrentPrincipal.Identity.IsAuthenticated instead of HttpContext.User.Identity.IsAuthenticated as System.Web.Mvc.AuthorizeAttribute does.
You need to populate this Principal on each request, usually by using a DelegatingHandler, which is explained on this link:
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
In the link above, the author is using Basic HTTP Authentication, which transmit the credentials in plain text on each request; but you can implement your own authentication strategy in order to populate the Principal, which is all you need.
来源:https://stackoverflow.com/questions/15999437/configuring-webapi-for-forms-authentication