Search code examples
asp.netasp.net-mvcforms-authentication

Difference between these two Authentication Ticket making ways?


I came across this part of code in a MVC Application

  var authTicket = new FormsAuthenticationTicket(
                                                           1,                             // version
                                                           oModel.UserID,                      // user name
                                                           DateTime.Now,                  // created
                                                           DateTime.Now.AddDays(30),   // expires
                                                           oModel.RememberMe,                   // persistent?
                                                           "Jt_AutoLogin"
                                                           );
                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        var authCookie = new HttpCookie("Jt_AutoLogin", encryptedTicket);
                        if (authTicket.IsPersistent)
                        {
                            authCookie.Expires = authTicket.Expiration;
                        }
                        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

and there was this code

FormsAuthentication.SetAuthCookie(oModel.UserID, oModel.RememberMe);

As far as I know, SetAuthCookie() method generates the authenticated ticket and adds it to the cookie collection.

But what about the first way?

If they are both indeed doing the same thing then what is the difference?


Solution

  • they both work

    The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection or the URL

    the first one

    var authTicket = new FormsAuthenticationTicket

    allow you to add more user define data to it like expiration etc..

    https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie(v=vs.110).aspx

    https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication(v=vs.110).aspx