prevent重定向未授权

prevent重定向未授权

本文介绍了MVC6 prevent重定向未授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET MVC的Web 6 API的应用程序,与AngularJs前端。

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

当我离开一个会议,十年,或者我想调用Web API擅自行动,我希望收到401状态code。
相反,我得到了302,并试图重定向到默认路径进行登录(/帐号/登录)。

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.

从其他论坛的帖子在这里和谷歌上搜索,我发现有些人使用startup.cs解决了自己的问题:

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;
});

没有运气我。

我用的身份为认证后端,甚至加入

I use Identity as authentication backend and even adding

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

不给我预期的结果。 ASP.NET文档表明这种方法返回一个401。

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

使用1.0.0-同β7CLR 86,IIS防爆preSS。

Using 1.0.0-beta7 CLR x86, IIS Express.

推荐答案

终于来了!我找到了解决办法!

Finally! I found the solution!

要完成,我开始与这个评论在ASPNET /身份的GitHub源$ C ​​$ C找到。

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.

与ConfigureIdentityApplicationCookie选项调试挖,我发现有一个代表对通知的属性。

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

OnApplyRedirect

宾果!

现在我可以控制的重定向。

Now I can control the redirect.

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

这可能不是处理问题的好办法,但最后我收到一个401未授权时web.api动作叫做无需认证。

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.

这篇关于MVC6 prevent重定向未授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:37