English 中文(简体)
creating a persisted cookie with forumsauthentication
原标题:

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

FormsAuthentication.SetAuthCookie(userId.ToString(), true);
问题回答

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">
<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>




相关问题
c# FormsAuthentication signOut another user

I m using formsAuthentication and as an admin user to the site i would like to be able to sign another user out. Is this possible ?

Hosted Silverlight LOB Application - Authentication Models

Our application is built in VB6 and delivered in a SaaS model via Citrix. Our subscribers must first authenticate to the Citrix Login Portal (AD) which gives them access to their applications. Each ...

ASP.Net Session Not Invalidated After Logout

I have a ASP.Net application in my login page I call FormsAuthentication.SignOut Session.Abandon() Session.Clear() however the Appscan is taking the ASPXAUTH cookie value then after logout is ...

热门标签