MVC6 Prevent unauthorized redirects

I am developing an ASP.NET MVC 6 Web API application with an AngularJs interface.

When I leave a session before a decade, or I try to invoke a web API action unauthorized, I expect to get a status code 401. Instead, I get 302 and try to redirect the default login path ("/ Account / Login").

So I need to handle this in Angular.

From other forum posts here and googling, I found that some people solved their problems using startup.cs:

services.Configure<CookieAuthenticationOptions>(options => { options.LoginPath = PathString.Empty; }); 

I was not lucky.

I use Identity as authentication and even add

 services.ConfigureIdentityApplicationCookie(options => { options.LoginPath = PathString.Empty; }); 

does not give the expected result. ASP.NET docs offer this way to return 401.

Using 1.0.0-beta7 CLR x86, IIS Express.

+1
angularjs asp.net-core-mvc unauthorized
source share
3 answers

For me, this worked just to set the AutometicAuthenticate parameter to false.

  services.Configure<IdentityOptions>(options => { options.Cookies.ApplicationCookie.AutomaticAuthenticate = false; options.Cookies.ApplicationCookie.AutomaticChallenge = false; options.Cookies.ApplicationCookie.LoginPath = PathString.Empty; }); 
+3
source share

EDIT : The solution proposed by @EZI is correct. Below is my answer, which does not work in a recent release.

At last! I have found a solution!

To be complete, I started with this comment found in the source code on the aspnet / Identity github.

 // If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs. 

which give me the wrong directions.

Delving into debugging ConfigureIdentityApplicationCookie parameters, I found that there is a delegate in the Notifications property

 OnApplyRedirect 

Bingo!

Now I can control the redirection.

 services.ConfigureIdentityApplicationCookie(options => { options.LoginPath = PathString.Empty; options.Notifications = new CookieAuthenticationNotifications { OnApplyRedirect = context => { context.Response.StatusCode = 401; } }; }); 

This may not be a good way to deal with this problem, but finally I get 401 Unauthorized when the web.api action gets called without authentication.

+6
source share

my solution was like @Ezi

Confirmed work for RC2

 services.AddIdentity<IdentityUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.AutomaticChallenge = false; }); 
+1
source share

All Articles