Allow anonymous to ASP.NET Web API controller while rest of the application runs under windows authentication

ぃ、小莉子 提交于 2019-11-28 12:04:12

I'm a bit late to the party, but ensure that Anonymous Authentication is enabled. Then add:

<configuration>
  ...
  <location path="api/...">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>
</configuration>

To your web.config.

I am assuming you have:

<system.web>
  ...
  <authentication mode="Windows" />
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

This worked for me.

Well - all controllers that need authentication need the Authorize attribute (that could be a global filter) - then use AllowAnonymous on the ones that don't need authN.

Then make sure anonymous authentication is enabled in IIS for the vdir - and also make sure there is no global authorize element in web.config.

The way I solved the problem, using Visual Studio 2015 and .NET 4.5.2, was to set the Web API project properties to have both Anonymous Authentication and Windows Authentication set to Enabled (note these will also have to be set in the IIS instance). Then within my controllers I decorated the methods that would require authentication with the [Authorize] attribute as well as the name of my custom authentication attribute.

This permitted the default configuration for the controller methods to accept anonymous calls and only the few special methods that required authentication had the extra decorators. I didn't have to add anything to the web.config or WebApiConfig.cs files. The Global.asax did have a call to my custom authentication static function which set global values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!