简体   繁体   中英

FormsAuthentication Cookie Not Saving

I have two login pages. One for admin users and one for customers.

They both execute the below code (after authorisation) to add a cookie to the Response . The two pages then redirect to the URL provided (I don't do the redirect here as I do some extra checks on admin)

public static string SetAuthCookie<T>
    (this HttpResponse responseBase, string name, bool rememberMe, T userData)
{
    /// In order to pickup the settings from config, we create a default cookie 
    /// and use its values to create a new one.
    var cookie = FormsAuthentication.GetAuthCookie(name, true);
    var ticket = FormsAuthentication.Decrypt(cookie.Value);

    var newTicket = new FormsAuthenticationTicket(
        ticket.Version, 
        ticket.Name, 
        ticket.IssueDate, 
        ticket.Expiration,
        true,
        Newtonsoft.Json.JsonConvert.SerializeObject(userData), 
        ticket.CookiePath
        );

    var encTicket = FormsAuthentication.Encrypt(newTicket);

    /// Use existing cookie. Could create new one but would have to copy settings over...
    cookie.Expires = (rememberMe ? DateTime.Now.AddDays(62) : DateTime.MinValue);

    cookie.Value = encTicket;

    responseBase.Cookies.Set(cookie);

    return FormsAuthentication.GetRedirectUrl(name, true /*This Is Ignored*/);
}

Admin
Now the admin does as it's told. Adds the cookie and redirects to an admin welcome screen.

Customer
The customer login area just isn't doing the same (see below screengrab).

  1. It posts (as you can see it receives the request to save the cookie)
  2. It redirects
  3. But, oh no, the next request has no cookie
  4. The system can't see the user is authenticated
  5. Back to the login screen we go

重定向过程

I thought that the problem may be a local browser.
Nope, tried: different browsers, using private/incognito.

I thought it might be the setting of the cookie.
How can it be? They both use the same code.

Maybe web.config (in their respected directories)?
Nope, just <authorization> rules

Maybe a problem with the cookie?
Nope, looks fine. Same domain, HTTPS. all fine

Something to do with RememberMe ?
Nope, tried both with and without

Soooo.... Been silly.

I forgot to exclude ( [JsonIgnore] ) a property that fetches some extra data (not needed for setting the cookie). This was being included and, obviously, made my cookie too large to save.

Oops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM