【问题标题】:MVC 4 Forms authentication strange behaviorMVC 4 Forms 身份验证奇怪的行为
【发布时间】:2013-08-22 05:48:40
【问题描述】:

我正在使用带有 MVC 4 的 Asp.Net 来构建 Web 应用程序。对于身份验证,我使用的是表单身份验证。登录页面设置正确,登录行为正常。但是,我没有使用默认的部分登录视图,而是使用我自己的并使用 AJAX 登录。

登录控制器工作正常,这里是登录代码。

这是我在登录操作中的代码。这里 resp 是我的自定义响应对象

resp.Status = true;
// sometimes used to persist user roles
string userData = "some user data";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  1,                                     // ticket version
  login.username,                        // authenticated username
  DateTime.Now,                          // issueDate
  DateTime.Now.AddMinutes(30),           // expiryDate
  false,                          // true to persist across browser sessions
  userData,                              // can be used to store additional user data
  FormsAuthentication.FormsCookiePath);  // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
//Response.Cookies.Add(cookie);
Response.SetCookie(cookie);

return Json(resp);

这是处理这个脚本响应的cshtml页面代码

function (respData) {
                    if (respData.Status) {
                        window.location.href = "/";
                    }
                    if (!respData.Status) {
                        if (respData.Errors[0].ErrorCode == 1) {
                            $('#invalid').show();
                            $('#username').val('');
                            $('#password').val('');
                        }
                        else if (respData.Errors[0].ErrorCode == -1) {
                            var msg = respData.Errors[0].ErrorDescription;
                            $('#error_email').text(msg);
                        }
                        else {
                            var msg = respData.Errors[0].ErrorDescription;
                            $('#error_pwd').text(msg);
                        }
                    }
                    $("#dialog").dialog("close");
                },

一切正常,用户成功登录后成功重定向到主页。还会收到有关失败的正确消息。

问题是,当我在重定向成功后浏览任何其他页面时,后续请求都没有经过身份验证。

我做了一些研究,发现浏览器没有在后续请求中发送表单身份验证 cookie,因此这些请求没有经过身份验证。

对此行为有任何想法吗? ,我错过了什么吗?

【问题讨论】:

  • 您的 web.config 中有哪些 FormsAuthentication 设置?我想知道 cookie PATH 设置为什么。

标签: asp.net-mvc jquery forms-authentication


【解决方案1】:

尝试使用以下命令明确设置 cookie 的过期时间:

Cookie.Expires(DateTime.Now.AddMinutes(30));

【讨论】:

  • 试过了。没有改变。更奇怪的是,它实际上是在下一个请求中发送 cookie,而不是后续请求。
猜你喜欢
  • 2010-12-17
  • 2011-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 1970-01-01
相关资源
最近更新 更多