c# - ASP.NET 身份验证 cookie

标签 c# .net asp.net authentication

在具有基于表单的身份验证的应用程序上,我有一个标准的 ASP.NET 登录控件和以下 Authenticate 事件处理程序。

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 Specifies that cookies are used, if the device profile supports cookies; otherwise, cookies are not used.For desktop browsers that are known to support cookies, a probing mechanism will be used to try to use cookies, when enabled. If a device does not support cookies, no probing mechanism will be used.

FormsAuthentication.SetAuthCookie : Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, using the supplied cookie path, or using the URL if you are using cookieless authentication.

我原以为在我的场景中,会使用无 cookie 身份验证,但事实并非如此(无论如何,我在重定向后在 QueryString 中看不到任何内容)。

如果我在 RedirectFromLoginPage 函数中设置断点并测试我得到的一些值:

bool cookieSupport = Request.Browser.Cookies; //"true"
bool redirectWithCookies = Request.Browser.SupportsRedirectWithCookie; //"true"
HttpCookieMode currentMode = FormsAuthentication.CookieMode; //"AutoDetect"

我不确定此处的 Request.Browser.Cookies 是否为真。浏览器确实支持 cookie,但它们都被阻止了......

无论如何,我在出现问题的机器上进行了几分钟的远程操作。隐私设置设置为中等,因此它应该能够接受 cookie。这是一个标准的 Win7/IE8 设置。我尝试将网站添加到用户的信任区域,以通过 https 登录,但没有成功。其他问题设置类似(机器没有真正突出,用户告诉我他们在其他网站上没有问题)

那么我做错了什么?

最佳答案

您是否在 web.config 文件中指定了表单例份验证 cookie 的域?它是否与网站的域相匹配?

我相信 IE 中的中等安全设置会阻止第三方 cookie,因此问题可能是 IE 认为您的身份验证 cookie 是第三方 cookie。

关于c# - ASP.NET 身份验证 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5902853/

相关文章:

asp.net - 在 ascx 文件中使用 if 条件

C# 确定字典中的值

c# - 检查字符串的格式

c# - 在 C# 中发送 key "hangs"PC

.net - 如何在 C++/CLI 程序和 C++/CLI DLL 之间传递字节数组?

c# - 从派生类调用的虚拟方法中的 typeof this

asp.net - paypal express沙箱几天前无法使用

asp.net - 从 Web 角色设置配置 ASP.NET SQL 成员资格提供程序

c# - 在 C# 中附加到鼠标的工具提示

C# - 划分列表的优雅方式?