0

I have two controllers;

  • AccountController : Controller //For accounts <-- MVC
  • ItemController : ApiController //For Items <-- WEB API

The accounts controller is for all intents and purposes a pretty standard implementation of the Accounts code, the only major difference is that it's using a Custom MembershipProvider. On the accounts controller I also have one other Action:

[Authorize]
public ActionResult Bleh(){ return View(); }

Which if I attempt to get to:

http://localhost/Account/Bleh

Redirects me (as expected) to the Login page, which after logging in, returns me back to the Bleh page. All good. The problem is on the ItemController, I have an Action which too has an Authorize attribute on it:

[Authorize]
public HttpResponseMessage PostItem(Item item) { /**/ }

Going to this before logging in returns a 401 - Unauthorized - which again is as expected, but after logging in, it still returns a 401. I can't see why this is the case.

Am I missing any configuration elements? Routing? N.E. Other?

I was under the impression that Web Api would pick up the Forms Authentication in the same way as MVC, and I know the authentication is working as the MVC one is working.

Charlotte Skardon
  • 6,220
  • 2
  • 31
  • 42

3 Answers3

0

Make sure that in the web.config hosting your API controller you have defined the authentication scheme:

<authentication mode="Forms">
    <forms loginUrl="~/Account/LogOn" timeout="2400" />
</authentication>

or if you are using some other kind of custom authentication scheme that you are tracking users differently you might need to write a DelegatingHandler. Here's an example I wrote for Basic Authentication: https://stackoverflow.com/a/11536349/29407

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm for all intents and purposes using the default Forms scheme just a different provider. The MVC and API controllers are hosted in the same host - I have the bit there and the MVC version is working just fine... – Charlotte Skardon Aug 21 '12 at 07:02
0

I have rebuilt the application from scratch, and the forms code is working as expected now. I cannot for the life of me see any difference between my original code and the new code. I suspect maybe something in a config file somewhere, but after a pretty substantial amount of time it eludes me.

Charlotte Skardon
  • 6,220
  • 2
  • 31
  • 42
0

You can override OnRedirectToLogin Identity event and return response accordingly based on the fact that it is an API call (based on '/api/' in url)

Anit
  • 33
  • 8