Use Anonymous authentication in MVC4 on single controller when the whole application uses Windows Authenticaion

北城余情 提交于 2019-11-27 22:06:50

Add this to your Web.config. Here, my controller is named "WebhookController".

<location path="Webhook">
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</location>

See this KB article for more info.

Edit - As Erik mentioned below, in MVC applications you should not use web.config <authorization> tags for security. Instead, use [Authorize] attributes. Doing so will allow your [AllowAnonymous] attributes to work correctly. You can read more about this here.

The accepted answer seems to be out of date, so...

In your web.config, remove these lines:

<authorization>
  <deny users="?" />
</authorization>

In the solution explorer, click your project, then click f4 (or open the properties explorer). Enable Anonymous Authentication.

Now you're free to use the Authorize and AllowAnonymous Attributes. They're pretty straightforward, Authorize means the user needs to be authorized in order to access the action or controller, AllowAnonymous means the opposite. If an unauthorized user attempts to access a controller or action with the Authorize attribute, they'll be redirected to a login page. If you put Authorize on a controller it applies to all the controller's actions, except ones with AllowAnonymous.

web.config should not be touched as indicated here.

In order to achieve desired result AllowAnonymous and [Authorize] (and maybe some custom authorization attribute, if needed) should be used.

Steps to be performed:

  1. Ensure IIS has both Anonymous Authentication and Windows Authentication configured for the web application / web site

  2. All controllers should use [Authorize] attribute. This can be easily achieved if all inherit from a common controller class (e.g. BaseController / BaseApiController). E.g.:

    [Authorize]
    public class BaseController : System.Web.Mvc.Controller
    {
    
    }
    
    
    [Authorize]
    public class BaseApiController : System.Web.Http.ApiController
    {
    
    }
    
  3. Add [AllowAnonymous] attribute to all actions that are supposed to be anonymous. E.g.:

    [RoutePrefix("Api/Anonymous")]
    [Authorize]
    public class AnonymousController : ApiController
    {
        [HttpGet]
        [Route("GetServiceStatus")]
        [AllowAnonymous]
        public string GetServiceStatus()
        {
            return "OK";
        }
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!