Pergunta

I have a website using simple forms authentication, validating credentials with the database. It's working fine as it is. In my <system.web> within the web.config I have:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>  

I now have the need to add a small WebApi Controller to the site for an application to pull a list of objects from. It seems like, as far as the WebApi authentication goes, Basic authentication would be fine. I'll have the user credentials in the application, which can easily be passed up, encoded in the request header.

My issue is differentiating the MVC and WebApi authentication. First of all, is my solution a good idea, and easily implementable? Currently, in my WebApiConfig.cs I have :

GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicAuthenticationHandler(new AuthenticationService()));

and BasicAuthenticationHandler looks for the credentials in the header. However, with the MVC forms authentication, I'm unable to reach that area at all. When I hit the action in fiddler, I can see it redirects me straight to the MVC Account/Login page. How do avoid the redirection for my WebAPI calls?

Thank you for any guidance.

Foi útil?

Solução

Well, looks like it was a simple fix. The direct line after the web.config code I have above looked like:

  <authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
  </authentication>
  <authorization>
    <deny users="?" />
  </authorization>

and it looks like the authorization element was completely overwriting any [AllowAnonymous] I had - the only possible method to reach anonymously was the login page. Removing those 3 lines completely fixed my issue - I now use the [AllowAnonymous] attribute for my WebAPI page, and it applies the basic authentication correctly.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top