【问题标题】:MVC6 Prevent Redirect on unauthorizedMVC6 防止未经授权的重定向
【发布时间】:2015-10-07 11:03:22
【问题描述】:

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

当我将会话留到十年时,或者我试图调用未经授权的 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 文档建议以这种方式返回 401。

使用 1.0.0-beta7 CLR x86、IIS Express。

【问题讨论】:

    标签: angularjs asp.net-core-mvc unauthorized


    【解决方案1】:

    编辑:@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; } 
         };
    });
    

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

    【讨论】:

    • 有人有关于如何在asp.net core的发布版本中解决的信息吗?
    • 这似乎对我有用:services.AddIdentity&lt;myUser, IdentityRole&gt;(c =&gt; c.Cookies.ApplicationCookie.LoginPath = PathString.Empty
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我的解决方案类似于@Ezi

      确认为 RC2 工作

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

      【讨论】:

        猜你喜欢
        • 2016-04-18
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多