Persisting authentication cookies

Posted by Community Admin on 04-Aug-2018 19:19

Persisting authentication cookies

All Replies

Posted by Community Admin on 09-Jan-2013 00:00

Hello,

I have a custom login control developed in order to log users into our AMS system (Aptify) as well as Sitefinity (our AMS handles user synch). Everything seems to be working fine, the FedAuth and .ASPXAUTH cookies are being set and the user is logged in to both systems. However, the .ASPXAUTH and FedAuth cookies expire at the end of the session, so if the user closes his browser and comes back he appears to be logged out of Sitefinity. How do I make these cookies persist longer than just until the session ends?

My authentication code for Sitefinity is as follows:

01.private bool AuthenticateUser(string userName, string password)
02.
03.    using (var userManager = UserManager.GetManager())
04.    
05.        if (userManager.ValidateUser(userName, password))
06.        
07.            var user = userManager.GetUser(userName);
08. 
09.            HttpWebRequest tokenRequest = (HttpWebRequest)HttpWebRequest.Create(SitefinityClaimsAuthenticationModule.Current.GetIssuer());
10.            tokenRequest.Headers.Add("deflate", "true");
11.            tokenRequest.Headers.Add("realm", SitefinityClaimsAuthenticationModule.Current.GetRealm());
12.            tokenRequest.Headers.Add("wrap_name", userName);
13.            tokenRequest.Headers.Add("wrap_password", password);
14. 
15.            HttpWebResponse issuerResponse = (HttpWebResponse)tokenRequest.GetResponse();
16.            if (HttpStatusCode.Unauthorized != issuerResponse.StatusCode)
17.            
18.                using (StreamReader responseStream = new StreamReader(issuerResponse.GetResponseStream()))
19.                
20.                    string token = responseStream.ReadToEnd();
21.                    var separator = Request.RawUrl.Contains("?") ? "&" : "?";
22.                    Response.Redirect(Request.RawUrl + separator + token);
23.                
24.            
25. 
26.            SecurityManager.AuthenticateUser(UserManager.GetDefaultProviderName(), userName, password, false, out user);
27.            return true;
28.        
29.        return false;
30.    
31.

Any help is appreciated.

Posted by Community Admin on 14-Jan-2013 00:00

Hi Josh,

Here's a sample code, which authenticates the user and the user remains authenticated after he/she closes the browser:

protected void Page_Load(object sender, EventArgs e)
       
           LoginWithClaims("admin", "password");
       
  
       public void LoginWithClaims(string username, string password)
     
         var authMode = Config.Get<SecurityConfig>().AuthenticationMode;
  
         if (Telerik.Sitefinity.Security.Configuration.AuthenticationMode.Forms == authMode)
         
             //old code should work here.
         
         else if (Telerik.Sitefinity.Security.Configuration.AuthenticationMode.Claims == authMode)
          
              HttpWebRequest tokenRequest = (HttpWebRequest)HttpWebRequest.Create(SitefinityClaimsAuthenticationModule.Current.GetIssuer());
              tokenRequest.Method = "POST";
              var postDataString = string.Format("deflate=true&realm=0&wrap_name=1&wrap_password=2&sf_persistent=true&sf_domain=Default",
                                                 HttpUtility.UrlEncode(SitefinityClaimsAuthenticationModule.Current.GetRealm()),
                                                 HttpUtility.UrlEncode(username),
                                                 HttpUtility.UrlEncode(password));
              var postData = Encoding.UTF8.GetBytes(postDataString);
              tokenRequest.ContentLength = postData.Length;
              tokenRequest.ContentType = "application/x-www-form-urlencoded";
  
              var dataStream = tokenRequest.GetRequestStream();
              dataStream.Write(postData, 0, postData.Length);
              dataStream.Close();
              HttpWebResponse issuerResponse;
              try
              
                  CookieContainer cookieJar = new CookieContainer();
                  tokenRequest.CookieContainer = cookieJar;
                  issuerResponse = (HttpWebResponse)tokenRequest.GetResponse();
                  HttpContext.Current.Response.Headers.Add("Set-Cookie", issuerResponse.Headers["Set-Cookie"]);
                  //foreach (Cookie c in cookieJar.GetCookies(tokenRequest.RequestUri))
                  //
                  //    var myCookie = new HttpCookie(c.Name, c.Value);
                  //    HttpContext.Current.Response.Cookies.Add(myCookie);
                  //
              
              catch (Exception ex)
              
                  throw new UnauthorizedAccessException("Unauthorized authentication attempt!");
              
              using (StreamReader responseStream = new StreamReader(issuerResponse.GetResponseStream()))
              
                  string token = responseStream.ReadToEnd();
                  Response.Redirect("~/?" + token);
              
          
        
     
 
Keep in mind that this will work when your project is on IIS. 

Regards,
Jen Peleva
the Telerik team
Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items

Posted by Community Admin on 14-Jan-2013 00:00

Thank you Jen. One further question: is there a way to do this without the redirect at the end? As in, just validate and set the cookies on postback instead of having to redirect somewhere with the token querystring?

Posted by Community Admin on 17-Jan-2013 00:00

Hi Josh,

 I just wanted to clarify something. The problem with logging out after the browser is closed used to exist in our previous versions, but is fixed for 5.3. However, if you simply want to authenticate the user by code, the last line is required. The cookies is actually required for the STS, not for Sitefinity as a relying party. This is why the redirect has to be done. If you skip it the authentication will not pass properly and later you will have to make the redirect to the STS again. This can be done by requesting a secured page and will lead to a redirect to the STS and the user will get authenticated, because of the cookie.

Hope you find this information useful!

Greetings,
Jen Peleva
the Telerik team
Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items

This thread is closed