3

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

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

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 中的名称匹配,域是“/”,到期日期如预期(见下文)。

以下是我的 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>

应该注意的是,我还在我的 web.config 文件中添加了一个 machineKey 条目,这是基于此处一个非常相似的问题的建议(这并没有解决我的问题)。另外,作为参考,对于我的持久 cookie,上面的 timeout=525599 比一年少 1 分钟。

4

1 回答 1

4

我发现了问题:

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

浏览每个部分,我发现在该'system.web / httpModules'部分中我有一个<clear/>元素。这删除了<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>机器级 web.config 文件中定义的模块。将其重新添加可立即解决问题。

当我尝试使用 FormsAuthentication 方法并且甚至没有加载该模块时收到错误消息肯定会很好......

于 2011-09-19T15:08:19.303 回答