mvc6 未经授权会导致重定向

2023-12-26

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

我已经尝试过提到的内容here https://stackoverflow.com/questions/32990538/mvc6-prevent-redirect-on-unauthorized(同样的问题,使用较旧的测试版框架,我使用 1.0.0-rc1-final)。我没有通知命名空间(已在 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;
        });

每次登录失败(请忽略“确定”时返回的密码)并应导致空的 401 页面时,我会重定向到 /Account/Login。这里有什么技巧呢?


解决方案不是直接配置 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);
                }
            };
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mvc6 未经授权会导致重定向 的相关文章

随机推荐