6

In an ASP.NET 5 Application I configured MVC and Identity framework like this:

app.UseMvc(config=>{
    config.MapRoute("Default", "{controller}/{action}/{id?}", new
            {
                controller = "Home",
                action = "Index"
            });
});

and adding Identity Services :

   services.AddAuthentication();
   services.AddAuthorization();

   services.AddIdentity<CrmUser, CrmUserRole>(config => { 
         config.User.RequireUniqueEmail = true;
          })
          .AddUserStore<MongoUserStore>()
          .AddRoleStore<MongoUserStore>()
          .AddDefaultTokenProviders();

and

 app.UseIdentity()
    .UseCookieAuthentication(i => { i.LoginPath = "/Account/Login";});

The example is defined as this:

public class MyApiController : Microsoft.AspNet.Mvc.Controller
{
    [Authorize]
    public async Task<ActionResult> Foo()
    {
        return Ok();
    }
}

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.

As a result when calling an unauthorized api which requires authorization, I get an HTTP 200 and the Login page instead of an HTTP 401.

In a blog post by Shawn Wildermuth I found this

services.AddCookieAuthentication(config =>
    {
        config.LoginPath = "/Auth/Login";
        config.Events = new CookieAuthenticationEvents()
        {
            OnRedirect = ctx =>
            {
                if (ctx.Request.Path.StartsWithSegments("/api") &&
                ctx.Response.StatusCode == 200)
                {
                    ctx.Response.StatusCode =     (int)HttpStatusCode.Unauthorized;
                    return Task.FromResult<object>(null);
                }
                else
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                    return Task.FromResult<object>(null);
                }
            }
        };
    });

But should this really be the expected way to do this? For me this smells a little.

3
  • I suggest you open a issue at github.com/aspnet/identity Oct 28, 2015 at 7:04
  • good idea: posted it here: github.com/aspnet/Identity/issues/604 Oct 28, 2015 at 9:05
  • 2
    You get a redirect because the cookie authentication system handles the AuthorizationChallenge by redirecting to the path you specify. The controllers should NOT be able to directly influence this behaviour and to couple the cookie authentication to the controller ( or even MVC ) is a worse smell. You have to handle the OnRedirect as above, but we use other metadata on the request to make a decision, like the accept header ( application/json, text/html ), or is ajax request Oct 29, 2015 at 0:03

3 Answers 3

2

This issue has been fixed in RC1.

Check GitHub comment here: Issue

To upgrade to RC1, go to http://get.asp.net.

To be even more sure, you can also clear your %userprofile%\.dnx\ folder prior to getting the latest version.

1
  • How is this an answer? It is a link to the same question the OP posted in a comment saying they have raised on a different website. 1) This is a link-only answer 2) the link doesn't have a code sample just a link to a git commit, which you asked for (unless someone felt the need to impersonate you with the same username and pic)
    – ono2012
    Jul 25, 2017 at 17:00
0

One solution to this is send the request with a the following header:

[{"key":"X-Requested-With","value":"XMLHttpRequest"}]

Here is an example using Postman without the header returns 200 and login webpage html Screenshot of Postman not sending the header returns 200 and login webpage html]

With the header returns 401 and no content (note there is not a tick next to it) With the header returns 401 and no content

The sample app is based on the ASP.NET Core default solution with Individual User Authentication

Why this works: CookieAuthenticationEvents.OnRedirectToLogin() uses IsAjaxRequest(context.Request) to decide whether to return a 401 or a redirect. So you have to have a header that will make IsAjaxRequest(context.Request) return true. It appears like a lot of JavaScript libraries add this automatically for you if you call your API through AJAX, but you might be not be using them.

Related questions you might find helpful

This behaviour was introduced as a result of a request the OP put in (which they mention under the question)

link to the current version of CookieAuthenticationEvents.cs at time of writing.

0

One (work around) option is to make the coockie options to redirect you to a controller action returning (unauthorized) result Sorry I'm replying using my phone I'll try to enhance my answer when I'm using my PC...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.