MVC6 防止未经授权重定向

MVC6 Prevent Redirect on unauthorized

我正在开发 ASP.NET MVC 6 Web API 应用程序,带有 AngularJs 前端。

当我将会话保留到 decade 时,或者我试图调用未经授权的 Web API 操作时,我希望收到 401 状态代码。 相反,我收到 302,并尝试重定向到登录的默认路径 ("/Account/Login")。

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

从这里的其他论坛帖子和谷歌搜索我发现有些人使用 startup.cs:

解决了他们的问题
services.Configure<CookieAuthenticationOptions>(options =>
 {
     options.LoginPath = PathString.Empty;
});

我运气不好。

我使用 Identity 作为身份验证后端甚至添加

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

没有给我预期的结果。 ASP.NET 文档建议用这种方式 return 401。

使用 1.0.0-beta7 CLR x86,IIS Express。

编辑:@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' 选项,我发现 "Notifications" 属性

上有一个委托
OnApplyRedirect

宾果!

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

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

这可能不是解决问题的好方法,但最终我在未经身份验证调用 web.api 操作时收到 401 Unauthorized。

对我来说,只需将 AutometicAuthenticate 设置为 false 即可。

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

我的解决方案类似于@Ezi

已确认为 RC2 工作

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