【问题标题】:mvc6 unauthorized results in redirect insteadmvc6 未经授权导致重定向
【发布时间】:2016-04-18 16:12:06
【问题描述】:

当我从控制器返回 NotAuthorized IActionResult 时,我一直试图阻止重定向,但无论我如何尝试,NotAuthorized 都会被转换为重定向。

我已经尝试过提到的here(同样的问题,使用较旧的 beta 框架,我使用 1.0.0-rc1-final)。我没有 Notifications 命名空间(已在 rc1-final 中删除)。

这是我的登录控制器:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return Ok(model);
            }
            if (result.IsLockedOut)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
            }
            else
            {
                return HttpUnauthorized();
            }
        }
        return HttpUnauthorized();
    }

在 Startup.cs 中,我尝试了不同的变化:

        services.Configure<CookieAuthenticationOptions>(o =>
        {
            o.LoginPath = PathString.Empty;
            o.ReturnUrlParameter = PathString.Empty;
            o.AutomaticChallenge = false;
        });

每次登录失败(请忽略密码返回到 Ok)并且应该导致一个空的 401 页面时,我会重定向到 /Account/Login。这里有什么诀窍?

【问题讨论】:

  • 您是否尝试在登录页面上执行此操作?还是用于 REST API 身份验证?如果它是一个 API,你可能会看这个:wildermuth.com/2015/9/10/ASP_NET_5_Identity_and_REST_APIs
  • REST API,您的链接假定​​ Notifications 命名空间存在,但已被删除。链接的解决方案不再起作用。

标签: redirect asp.net-core identity asp.net-core-mvc unauthorized


【解决方案1】:

从身份 2.0 开始, 您需要添加:

using Microsoft.AspNetCore.Authentication.Cookies;

在 ConfigureServices 中:

services.ConfigureApplicationCookie(options =>
{
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = (x =>
        {
            if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
                x.Response.StatusCode = 401;

            return Task.CompletedTask;
        }),
        OnRedirectToAccessDenied = (x =>
        {
            if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
                x.Response.StatusCode = 403;

            return Task.CompletedTask;
        })
    };
});

路段检查当然应该根据您的路线进行调整。

【讨论】:

    【解决方案2】:

    如果您有一些需要重定向的页面和其他不应有重定向的 URL,请参阅此问题以获取仅对非 API URL 使用默认重定向逻辑的解决方案:

    Suppress redirect on API URLs in ASP.NET Core

    【讨论】:

      【解决方案3】:

      取自这里(Shawn Wildermuth --> ASP.NET 5 Identity and REST APIs --> "Mehdi Hanafi" 的评论)并使用 Postman 测试了 API

      config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
      {
          OnRedirectToLogin = ctx =>
          {
              if (ctx.Request.Path.StartsWithSegments("/api") &&
              ctx.Response.StatusCode == 200)
              {
                  ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                  return Task.FromResult<object>(null);
              }
              else
              {
                  ctx.Response.Redirect(ctx.RedirectUri);
                  return Task.FromResult<object>(null);
              }
          }
      };
      

      【讨论】:

      • 你如何让它首先重定向。我希望上帝能让我的重定向。它不会这样做。
      【解决方案4】:

      解决办法不是直接配置CookieAuthenticationOptions,而是通过IdentityOptions来做这样的:

              services.Configure<IdentityOptions>(o =>
              {
                  o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                  {
                      OnRedirectToLogin = ctx =>
                      {
                          if (ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                          {
                              return Task.FromResult<object>(null);
                          }
                          ctx.Response.Redirect(ctx.RedirectUri);
                          return Task.FromResult<object>(null);
                      }
                  };
              });
      

      【讨论】:

      • 简单地使用o.Cookies.ApplicationCookie.AutomaticChallenge = false; 对我来说就足够了(我从不想要重定向)。
      • @PeppeL-G 这是我唯一可以开始工作的事情。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多