MVC FormsAuthentication:身份验证重定向丢失 POST 参数

时间:2021-02-10 14:04:50

标签: asp.net-mvc forms-authentication

我有一个通过 web.config 启用 FormsAuthentication 的 mvc 网站:

   <authentication mode="Forms">
      <forms loginUrl="~/Login/Index" />
    </authentication>

我的问题是当用户等待大约一分钟(显然会话超时很短)并在页面上触发操作时,所有 POST 参数都丢失了。 会发生什么:

  • 用户在页面上并更改过滤器(仅限客户端)
  • 他提交表单 (POST) => 如果身份验证没有超时,则效果很好
  • 如果身份验证超时,用户将被重定向到 LoginController,通过 Index() 方法进行身份验证,并通过 returnUrl 重定向到上一页
  • 用户获得了他的页面,但 POST 参数丢失了(因为重定向)

这里是用户重定向时LoginController中的代码(这里的returnUrl参数是为了获取自动添加的参数):

 [HttpGet]
        public ActionResult Index(string returnUrl)
        {
            var model = new Models.Login.User()
            {
                IsAuthenticated = HttpContext.User.Identity.IsAuthenticated
            };
            if (model.IsAuthenticated && !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            else
                return View(model);
        }

我使用 HttpGet 是因为(我想)它是 FormsAuthentication 机制。

以及验证代码,当用户输入他的登录名和密码时,仍然在 LoginController 中:

        [HttpPost]
        public ActionResult Index(Models.Login.User user, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //Vérifie le ldap
                using (var pc = new PrincipalContext(ContextType.Domain))
                {
                    // validate the credentials
                    user.IsAuthenticated = pc.ValidateCredentials(user.UserInfo.Login, user.Password);
                    if (user.IsAuthenticated)
                    {
                        Code.Identity.UserInfo = Code.Identity.GetUser(user.UserInfo.Login);
                        FormsAuthentication.SetAuthCookie(user.UserInfo.Login, true);

                        if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                            return Redirect(returnUrl);
                        else return Redirect("/");
                    }
                    else
                        ModelState.AddModelError($"{nameof(user.Password)}", "Identifiant ou mot de passe incorrect");
                }
            }
            return View(user);
        }

我想要什么:

  1. 当用户仍然拥有他的身份验证 cookie 时,请避免这种重定向。由于 FormsAuthentication.SetAuthCookie(user.UserInfo.Login, true),它应该被存储; => FormsAuthentication 有选项吗?我是否必须覆盖 AuthenticationAttribute,如果需要,如何以最简单的方式实现?
  2. 能够在重定向时检索帖子参数(但确实应该有 FormAutentication 选项来这样做)

我对 FormsAuthentication、AuthorizationAttribute 进行了大量研究(但应该在身份验证后使用),我发现实现 FormsAuthentication 的方法只有 FormsAuthentication.SetAuthCookie()。

提前感谢您的建议。

0 个答案:

没有答案
相关问题