2015-10-07 46 views
1

我正在开发一个带有AngularJs前端的ASP.NET MVC 6 Web API应用程序。MVC6防止未经授权的重定向

当我离开会议十年,或者我试图调用未经授权的Web API操作时,我希望收到401状态码。 取而代之,我得到一个302,并尝试重定向到登录的默认路径(“/帐户/登录”)。

所以我需要在Angular中处理这个问题。

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

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

没有运气我。

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

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

不给我预期的结果。 ASP.NET文档建议以这种方式返回401.

使用1.0.0-beta7 CLR x86,IIS Express。

回答

3

对我来说,它只是将AutometicAuthenticate设置为false。

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

编辑:@EZI提出的解决方案是正确的。 下面我的答案,这不适用于最近的版本。

终于!我找到了解决方案!

为了完整起见,我从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. 

这给我错误的方向。

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

OnApplyRedirect 

宾果!

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

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

这也许不是处理问题的好办法,但最后我收到401未经授权当web.api动作叫做无认证。

+0

为RC1 – FLCL

+0

不工作是否有人有关于如何在asp.net核心的发行版本解决了信息工作的? – Maris

+0

这似乎对我有效:'services.AddIdentity (c => c.Cookies.ApplicationCookie.LoginPath = PathString.Empty' – GeorgDangl

1

我的解决方案是类似于@Ezi

证实RC2

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