Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AllowAnonymous Attribute not working on Web API controller

I have an web application written in ASP.NET MVC 4. It's an intranet application therefore I'm using Windows Authentication (Anonymous Authentication is turned off). It exposes some Web API services to other web applications.

The problem is that these services should be accessed by anonymous users from other applications. When I call the service from the browser everything works fine (which is obvious). But when I try to communicate with the service through another application it returns an 401.2 error. Decorating the API controller with anonymous attribute does not help. I tried too in web.config to set the location element like in the following code:

<location path="Controllers/Api">
<system.web>
  <authorization>
    <!-- All anonymous users access to the virtual path api -->
    <allow users="?" />
  </authorization>
</system.web>
<!-- Need to include the security overrides else it will inherit from the root of the application -->
<system.webServer>
  <security>
    <authentication>
      <!-- Need to enable anonymous access and turn off Windows authentication for the virtual path -->
      <anonymousAuthentication enabled="true"/>
      <windowsAuthentication enabled="false"/>
    </authentication>
  </security>
</system.webServer>

But it does not help either. In web.config I don't have any other sections set (I mean I don't have any authorization block).

Does anybody have any idea what is going on? Why doesn't it work? I would be grateful for any information on how I can resolve this problem.

This is my Web API action created for testing purposes:

[AllowAnonymous]
public class TestController : ApiController
{
    public string GetSayHello()
    {
        return "Hello world";
    }
}


Greetings.

like image 324
Roman Suska Avatar asked May 28 '15 12:05

Roman Suska


2 Answers

Check that IIS settings are indeed allowing anonymous access. It must have a misconfiguration in the server. One alternative is to use Fiddler for debugging. You are doing everything right from the application's perspective.

like image 104
beautifulcoder Avatar answered Oct 04 '22 10:10

beautifulcoder


A colleague of mine found out that you must set the location path with the actual url.
For example I have a controller named exampleController and you access it like this http://domain.com/api/example/method. Then you add the example below to your web.config. Visual studio will complain but it works.

<location path="api/example/method">
  <system.web>
    <authorization>
      <allow users="?" />
    </authorization>
  </system.web>
</location>
like image 32
Arin Avatar answered Oct 04 '22 11:10

Arin