How to remove redirection from ASP.NET 5 webapi and return HTTP 401?

After answering this question , I added authorization to everyone by default, using the following code:

public void ConfigureServices(IServiceCollection aServices) { aServices.AddMvc(options => { var lBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser(); var lFilter = new AuthorizeFilter(lBuilder.Build()); options.Filters.Add(lFilter); }); aServices.AddMvc(); } public void Configure(IApplicationBuilder aApp, IHostingEnvironment aEnv, ILoggerFactory aLoggerFactory) { aApp.UseCookieAuthentication(options => { options.AuthenticationScheme = "Cookies"; options.AutomaticAuthentication = true; }); } 

However, when someone tries to access something unauthorized, he returns a redirect URL (which seems by default) ( http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F ).

I want it to return only HTTP 401, not a redirect.

How to do this in ASP.NET 5 for WebAPI?

+7
authorization asp.net-web-api asp.net-core
source share
5 answers

You are being redirected to the URL, I assume that you are using cookie authentication.

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

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

It probably worked then, but it no longer works (because of this ).

I posted an error on GitHub for this.

I will update the answer as soon as it is fixed.

+5
source

I had this problem in an Angular2 + ASP.NET Core application. I managed to fix it as follows:

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

If this does not work for you, you can try with the following method:

 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 settings are now configured as follows:

 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); } }; }); 
+11
source

Setting LoginPath = "" or null no longer works in version 1.1.0.0. So here is 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, }); 
+4
source

Remember that you should not use CookieAuthentication only if you want to use your own authentication mechanism, for example, bypassing the Identity provider, which is not suitable for most of us.

By default, the Identity provider uses CookieAuthenticationOptions behind the scenes, you can configure it as shown below.

 services.AddIdentity<ApplicationUser, IdentityRole>(o => { o.Password.RequireDigit = false; o.Password.RequireUppercase = false; o.Password.RequireLowercase = false; o.Password.RequireNonAlphanumeric = false; o.User.RequireUniqueEmail = true; o.Cookies.ApplicationCookie.LoginPath = null; // <----- }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); 

Tested in version 1.0.0

+1
source

in case this helps, below is my answer - with dotnet 1.0.1

based on Darkseal's answer, except that I had to add the line ctx.Response.WriteAsync () to stop the redirect to the default 401 URL (account / login)

  // Adds identity to the serviceCollection, so the applicationBuilder can UseIdentity services.AddIdentity<ApplicationUser, IdentityRole>(options => { //note: this has no effect - 401 still redirects to /Account/Login! //options.Cookies.ApplicationCookie.LoginPath = null; options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { //for WebApi: prevent aspnet core redirecting to 'Account/Login' on a 401: if (ctx.Request.Path.StartsWithSegments("/api")) { ctx.RedirectUri = null; ctx.Response.WriteAsync("{\"error\": " + ctx.Response.StatusCode + "}"); } else { ctx.Response.Redirect(ctx.RedirectUri); } return Task.FromResult(0); } }; }) .AddDefaultTokenProviders(); } 
0
source

All Articles