为什么ASP.NET FormsAuthentication cookie未对用户进行身份验证?

为什么ASP.NET FormsAuthentication cookie未对用户进行身份验证?,asp.net,cookies,membership,formsauthentication,Asp.net,Cookies,Membership,Formsauthentication,我有一个使用默认SqlMembershipProvider和FormsAuthentication的站点。我可以使用内置的登录控件和/或以编程方式调用所有方法对用户进行身份验证,并获得相同的结果-用户经过身份验证并创建cookie,但cookie似乎无效,因为我无法进入任何需要身份验证的页面 默认登录控件没有真正的代码显示,因为它应该只是“工作”,但下面是我尝试的自定义代码: protected void ctrlLogin_Authenticate(object sender, Authent

我有一个使用默认SqlMembershipProvider和FormsAuthentication的站点。我可以使用内置的登录控件和/或以编程方式调用所有方法对用户进行身份验证,并获得相同的结果-用户经过身份验证并创建cookie,但cookie似乎无效,因为我无法进入任何需要身份验证的页面

默认登录控件没有真正的代码显示,因为它应该只是“工作”,但下面是我尝试的自定义代码:

protected void ctrlLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
   if (Membership.ValidateUser(ctrlLogin.UserName, ctrlLogin.Password))
   {
      FormsAuthentication.RedirectFromLoginPage(ctrlLogin.UserName, ctrlLogin.RememberMeSet);
      /*
       * I also tried this:
      FormsAuthentication.SetAuthCookie(ctrlLogin.UserName, ctrlLogin.RememberMeSet);
      if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
         Response.Redirect(Request.QueryString["ReturnUrl"]);
      Response.Redirect("/index.aspx");
       */
   }
   else
   {
      ctrlLogin.FailureText = "Invalid Username/Password Combination";
   }
}
使用此代码,Membership.ValidateUser()成功,并且FormsAuthentication.RedirectFromLoginPage()和FormsAuthentication.RedirectFromLoginPage()都成功设置了cookie-该cookie无法验证我的身份验证。我已经确认了这一点,删除了我所有的cookie,并看着它们再次被FireCookie创建。cookie名称与我在web.config中的名称匹配,域为“/”,过期日期如预期(见下文)

以下是my web.config的相关部分:

<authentication mode="Forms">
  <forms loginUrl="~/login/index.aspx" name=".SoeAuth" protection="All"
    slidingExpiration="true" timeout="525599" domain=""></forms>
</authentication>
<membership defaultProvider="SqlMembershipProvider">
  <providers>
    <add connectionStringName="[MY_CS]" applicationName="[MY_APPNAME]"
      minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
      enablePasswordReset="true" passwordFormat="Hashed" requiresUniqueEmail="true"
      name="SqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"
      requiresQuestionAndAnswer="false"/>
  </providers>
</membership>
(这并没有解决我的问题)。另外,作为参考,上面的超时=525599比我的持久cookie的一年少1分钟。

我发现了问题:

因为我能够用完全相同的源代码创建一个简单的工作测试项目,所以我确定问题出在web.config文件中

通过查看每个部分,我发现在
'system.web/httpModules'
部分中有一个
元素。这删除了机器级web.config文件中定义的
模块。将其添加回后,立即解决了问题


当我尝试使用FormsAuthentication方法时,如果收到一条错误消息,而该模块甚至没有加载,那当然会很好。

我知道ValidateUser实际上没有设置cookie。我要指出的是,当以编程方式验证用户时,这是必需的,它证明了我不仅仅是输入了错误的用户名或密码。上面的代码显示了整个过程。登录后重新访问时,
IsAuthenticated
设置为什么?我认为RedirectFromLoginPage也不会设置身份验证cookie,除非在特定情况下。User.Identity.IsAuthenticated为false。请尝试在表单配置中设置/的路径,它可能会按原样工作。只有当
CookiesSupported | | IsPathWithinAppRoot(current,returnUrl))
时才会设置cookie,否则只需在重定向之前显式调用SetAuthCookie即可。cookie是否在下一个请求中发送(使用fiddler并检查请求头)并且对于傻笑,请将超时降低到600以进行测试。同时删除域“”-您没有设置它,因此请删除它。您是如何添加它的?当我面临同样的问题时,要么删除,要么在下面添加元素。花了很多时间试图找出它为什么不进行身份验证。在较新的版本中,它可能是一个元素。向上投票的答案