Valerio Valerio - 1 year ago 195
AngularJS Question

MVC6 Prevent Redirect on unauthorized

I'm developing an ASP.NET MVC 6 Web API app, with AngularJs frontend.

When I leave a session to decade, or I'm trying to call a Web API action unauthorized, I expect to receive a 401 status code.
Instead, I get a 302, and tries to redirect to the default path for login ("/Account/Login").

So I need to handle this in Angular.

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

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

No luck for me.

I use Identity as authentication backend and even adding

services.ConfigureIdentityApplicationCookie(options =>
options.LoginPath = PathString.Empty;

does not give me the expected result. ASP.NET docs suggest this way to return a 401.

Using 1.0.0-beta7 CLR x86, IIS Express.

Answer Source

Finally! I found the solution!

To be complete, I started with this comment found on source code in 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.

Digging with debug on ConfigureIdentityApplicationCookie' options, I found that there is a delegate on "Notifications" property



Now I can control the redirect.

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

This maybe isn't a good way to handle the problem, but finally I receive a 401 Unauthorized when the web.api action is called without authentication.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download