问题
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.
回答1:
For me it worked to just set the AutometicAuthenticate to false.
services.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.AutomaticAuthenticate = false;
options.Cookies.ApplicationCookie.AutomaticChallenge = false;
options.Cookies.ApplicationCookie.LoginPath = PathString.Empty;
});
回答2:
EDIT: the solution proposed by @EZI is correct. Below my answer, which doesn't work on recent release.
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
OnApplyRedirect
Bingo!
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.
回答3:
my solution was similar to @Ezi
Confirmed working for RC2
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AutomaticChallenge = false;
});
来源:https://stackoverflow.com/questions/32990538/mvc6-prevent-redirect-on-unauthorized