title: ASP.NET Unauthorized access on a controller should return 401 instead of 200 and the login page
body: <p>In an <code>ASP.NET 5</code> Application I configured MVC and Identity framework like this:</p>
  
  
  
  <pre class="lang-cs prettyprint-override"><code>app.UseMvc(config=&gt;{
      config.MapRoute("Default", "{controller}/{action}/{id?}", new
              {
                  controller = "Home",
                  action = "Index"
              });
  });
  </code></pre>
  
  <p>and adding Identity Services :</p>
  
  <pre class="lang-cs prettyprint-override"><code>   services.AddAuthentication();
     services.AddAuthorization();
  
     services.AddIdentity&lt;CrmUser, CrmUserRole&gt;(config =&gt; { 
           config.User.RequireUniqueEmail = true;
            })
            .AddUserStore&lt;MongoUserStore&gt;()
            .AddRoleStore&lt;MongoUserStore&gt;()
            .AddDefaultTokenProviders();
  </code></pre>
  
  <p>and </p>
  
  <pre class="lang-cs prettyprint-override"><code> app.UseIdentity()
      .UseCookieAuthentication(i =&gt; { i.LoginPath = "/Account/Login";});
  </code></pre>
  
  <p>The example is defined as this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class MyApiController : Microsoft.AspNet.Mvc.Controller
  {
      [Authorize]
      public async Task&lt;ActionResult&gt; Foo()
      {
          return Ok();
      }
  }
  </code></pre>
  
  <p>This works fine, but i also have some controller which I want to use in a API way. In ASP.NET 5, they all have same base class so there is no difference between API and View Controllers.</p>
  
  <p>As a result when calling an unauthorized api which requires authorization, I get an <code>HTTP 200</code> and the Login page instead of an <code>HTTP 401</code>.</p>
  
  <p>In a blog post by <a href="http://wildermuth.com/2015/9/10/ASP_NET_5_Identity_and_REST_APIs" rel="nofollow">Shawn Wildermuth</a> I found this</p>
  
  <pre class="lang-cs prettyprint-override"><code>services.AddCookieAuthentication(config =&gt;
      {
          config.LoginPath = "/Auth/Login";
          config.Events = new CookieAuthenticationEvents()
          {
              OnRedirect = ctx =&gt;
              {
                  if (ctx.Request.Path.StartsWithSegments("/api") &amp;&amp;
                  ctx.Response.StatusCode == 200)
                  {
                      ctx.Response.StatusCode =     (int)HttpStatusCode.Unauthorized;
                      return Task.FromResult&lt;object&gt;(null);
                  }
                  else
                  {
                      ctx.Response.Redirect(ctx.RedirectUri);
                      return Task.FromResult&lt;object&gt;(null);
                  }
              }
          };
      });
  </code></pre>
  
  <p>But should this really be the expected way to do this? For me this smells a little.</p>