How to remove the redirect from an ASP.NET Core webapi and return HTTP 401? How to remove the redirect from an ASP.NET Core webapi and return HTTP 401? asp.net asp.net

How to remove the redirect from an ASP.NET Core webapi and return HTTP 401?


I had with this problem in an Angular2 + ASP.NET Core application. I managed to fix it in the following way:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {    // ...    config.Cookies.ApplicationCookie.AutomaticChallenge = false;    // ...});

If this is not working for you, you can try with the following method instead:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {    // ...    config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents    {       OnRedirectToLogin = ctx =>       {           if (ctx.Request.Path.StartsWithSegments("/api"))            {               ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;               // added for .NET Core 1.0.1 and above (thanks to @Sean for the update)               ctx.Response.WriteAsync("{\"error\": " + ctx.Response.StatusCode + "}");           }           else           {               ctx.Response.Redirect(ctx.RedirectUri);           }           return Task.FromResult(0);       }    };    // ...}

Update for Asp.Net Core 2.0

Cookie options are now configured in the following way:

services.ConfigureApplicationCookie(config =>            {                config.Events = new CookieAuthenticationEvents                {                    OnRedirectToLogin = ctx => {                        if (ctx.Request.Path.StartsWithSegments("/api"))                        {                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                        }                        else {                            ctx.Response.Redirect(ctx.RedirectUri);                        }                        return Task.FromResult(0);                    }                };            });


By the url you get redirected to I assume you're using cookie authentication.

You should get the desired results by setting the LoginPath property of the CookieAuthenticationOptions to null or empty as described by one of the users.

app.UseCookieAuthentication(options =>        {            options.LoginPath = "";        });

It was probably working back then but it's not working anymore (because of this change).

I've submitted a bug on GitHub for this.

I'll update the answer once it gets fixed.


Setting LoginPath = "" or null no longer works on Version 1.1.0.0. So here's what I did:

app.UseCookieAuthentication(new CookieAuthenticationOptions()        {            ExpireTimeSpan = TimeSpan.FromDays(150),            AuthenticationScheme = options.Cookies.ApplicationCookie.AuthenticationScheme,            Events = new CookieAuthenticationEvents            {                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync,                OnRedirectToLogin = async (context) => context.Response.StatusCode = 401,                OnRedirectToAccessDenied = async (context) => context.Response.StatusCode = 403            },            AutomaticAuthenticate = true,            AutomaticChallenge = true,        });