【发布时间】:2011-09-16 20:49:14
【问题描述】:
我有一个使用默认 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 中的名称匹配,域是“/”,到期日期如预期(见下文)。
这是我的 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>
应该注意的是,我还根据a very similar question here 的建议在我的 web.config 文件中添加了一个 machineKey 条目(这并没有解决我的问题)。另外,作为参考,对于我的持久 cookie,上面的 timeout=525599 比一年少 1 分钟。
【问题讨论】:
-
我知道 ValidateUser 实际上并没有设置 cookie。我要提到的一点是,在以编程方式验证用户身份时这是必需的,它证明我不只是输入了错误的用户名或密码。上面的代码展示了整个过程。
-
登录后重新访问时
IsAuthenticated设置为什么?我认为 RedirectFromLoginPage 也不会设置身份验证 cookie,除非在特定情况下。 -
User.Identity.IsAuthenticated 为假。
-
尝试在表单配置中设置 / 的路径,它可能会按原样工作。 cookie 仅在
CookiesSupported || IsPathWithinAppRoot(current, returnUrl))时设置,否则在重定向前显式调用 SetAuthCookie。 -
是您在下一个请求中发送的 cookie(使用 fiddler 并检查请求标头),为了傻笑,将超时时间降低到 600 以进行测试。同时删除 domain="" - 你没有设置它所以删除它。
标签: asp.net cookies membership formsauthentication