在一个基于表单认证的应用程序中,我有一个标准的ASP.NET登录控件,具有以下Authenticate事件处理程序。
RedirectFromLoginPage函数的用法如下:
我不确定这里的Request.Browser.Cookies是否应该为true。浏览器确实支持cookies,但它们全部被阻止了... 无论如何,我可以远程控制出现问题的机器几分钟。隐私设置被设置为中等,所以它应该能够接受cookies。这是一个标准的Win7/IE8设置。我尝试将网站添加到用户的可信任区域,通过https登录,但没有成功。其他出现问题的设置类似(机器上没有什么特别之处,用户告诉我他们在其他网站上没有问题)。那我做错了什么呢?
void Login_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Security.AuthenticateUser(Login.UserName, Login.Password))
{
e.Authenticated = true;
RedirectFromLoginPage(Login.UserName);
}
else
{
e.Authenticated = false;
}
}
RedirectFromLoginPage函数的用法如下:
private void RedirectFromLoginPage(String username)
{
String returnUrl = GetReturnUrl();
FormsAuthentication.SetAuthCookie(username, true, "/");
Response.Redirect(returnUrl, true);
}
这在99%的情况下都能正常工作。然而,有时我会接到一些用户无法登录的支持电话。他们会输入凭据,然后被重定向回首页(当一切正常时就是这样),但他们没有成功登录。
考虑到这可能是一个cookie问题,我尝试通过将我的隐私选项设置为“阻止所有cookie”来复现该问题,并且我成功地复现了该问题。调用了SetAuthCookie函数,但在下一页加载时,HttpContext.Current.User.Identity.IsAuthenticated
返回false。
在我的web.config中,身份验证设置如下:
<authentication mode="Forms">
<forms loginUrl="..." timeout="180" cookieless="AutoDetect"/>
</authentication>
在 MSDN 上阅读有关 AutoDetect 和 SetAuthCookie 的文档,我得到了以下信息:
AutoDetect:如果设备配置文件支持 cookie,则使用 cookie;否则不使用。对于已知支持 cookie 的桌面浏览器,将使用探测机制尝试使用启用 cookie 时的 cookie。如果设备不支持 cookie,则不会使用探测机制。
FormsAuthentication.SetAuthCookie:为提供的用户名创建身份验证票证,并将其添加到响应的 cookie 集合中,使用提供的 cookie 路径或 URL(如果使用无 cookie 身份验证)。
我本以为在我的场景中会使用无 cookie 身份验证,但实际上并没有(在重定向后我看不到 QueryString 中的任何内容)。
如果我在 RedirectFromLoginPage 函数中设置断点并测试一些值,我会得到:
bool cookieSupport = Request.Browser.Cookies; //"true"
bool redirectWithCookies = Request.Browser.SupportsRedirectWithCookie; //"true"
HttpCookieMode currentMode = FormsAuthentication.CookieMode; //"AutoDetect"
我不确定这里的Request.Browser.Cookies是否应该为true。浏览器确实支持cookies,但它们全部被阻止了... 无论如何,我可以远程控制出现问题的机器几分钟。隐私设置被设置为中等,所以它应该能够接受cookies。这是一个标准的Win7/IE8设置。我尝试将网站添加到用户的可信任区域,通过https登录,但没有成功。其他出现问题的设置类似(机器上没有什么特别之处,用户告诉我他们在其他网站上没有问题)。那我做错了什么呢?