views:

32

answers:

1

I am doing the following during login, but the logins don't seem to be persisting at all:

FormsAuthentication.SetAuthCookie(userId.ToString(), true);
+1  A: 

You have run into a bug that MS calls an undocumented security feature.

In order to set a persistent cookie you need to create it yourself and set the Expiration explicitly. The only trick is to get the FormsAuthentication timeout value, which, in their infinite wisdom, microsoft has not exposed since 1.0. I have provided my method for getting this value.

Here is a working example.

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"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<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>
Sky Sanders

related questions