使用forumsauthentication创建持久cookie

时间:2009-11-16 15:46:55

标签: forms-authentication

我在登录期间执行以下操作,但登录似乎根本不存在:

FormsAuthentication.SetAuthCookie(userId.ToString(), true);

1 个答案:

答案 0 :(得分:2)

您遇到了MS调用未记录的安全功能的错误。

要设置持久性cookie,您需要自己创建它并明确设置Expiration。唯一的技巧是获得FormsAuthentication超时值,这是一种无限的智慧,微软从1.0开始就没有暴露过。我提供了获取此值的方法。

这是一个有效的例子。

<强>的Login.aspx

<%@ Page Language="C#" %>

<script runat="server">

    protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        var login = (Login)sender ;

        if (login.RememberMeSet)
        {
            // hack to get forms timeout - it is not publicly surfaced anywhere. 
            var tmpTicket = FormsAuthentication.GetAuthCookie("foo", true);
            var timeout = tmpTicket.Expires;

            // create a new ticket
            FormsAuthenticationTicket ticket =
            new FormsAuthenticationTicket(2, login.UserName, DateTime.Now, timeout, true, "", FormsAuthentication.FormsCookiePath);


            string ticketEncrypted = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)
            {
                HttpOnly = true,
                Path = FormsAuthentication.FormsCookiePath,
                Secure = FormsAuthentication.RequireSSL,
                Expires = ticket.Expiration
            };

            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            Response.Cookies.Add(cookie);
        }
    }

</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Login ID="Login1" runat="server" OnLoggedIn="Login1_LoggedIn">
        </asp:Login>
    </div>
    </form>
</body>
</html>