mattematico
mattematico

Reputation: 669

Which FormsAuthentication method to use?

Im trying to make my own FormsAuthentication in an ASP.NET MVC 4 application and I have seen two different ways of creating my authcookie and I was wondering if one of them is having any disadvantages or if it is safe to use them both and are there any other differences I should know about before I decide witch to use?

the first one is

FormsAuthentication.SetAuthCookie(userName, rememberMe);

the other one is a bit longer

            var authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            DateTime.Now,
            DateTime.Now.AddMinutes(30),
            rememberMe,
            "Users"
            );
        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        HttpContext.Current.Response.Cookies.Add(authCookie);

please enlighten me about this decision

Upvotes: 4

Views: 2523

Answers (2)

Jesse van Assen
Jesse van Assen

Reputation: 2290

Actually, the first method calls the second method. I have taken the source of the SetAuthCookie to show this, but removed some lines to keep it relevant:

public static void SetAuthCookie(string userName, bool createPersistentCookie)
{
    FormsAuthentication.Initialize();
    FormsAuthentication.SetAuthCookie(userName, createPersistentCookie, FormsAuthentication.FormsCookiePath);
}

public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
    (...)
    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
    (...)
    HttpContext.Current.Response.Cookies.Add(authCookie);
    (...)
}

private static HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath, bool hexEncodedTicket)
{
    (...)
    DateTime utcNow = DateTime.UtcNow;
    DateTime expirationUtc = utcNow.AddMinutes((double) FormsAuthentication._Timeout);
    FormsAuthenticationTicket ticket = FormsAuthenticationTicket.FromUtc(2, userName, utcNow, expirationUtc, createPersistentCookie, string.Empty, strCookiePath);
    string str = FormsAuthentication.Encrypt(ticket, hexEncodedTicket);
    (...)
    HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);
    (...)
    return httpCookie;
}

Upvotes: 3

yogeswaran K
yogeswaran K

Reputation: 2288

second one is best.. because u can send user data, set expiration time etc..

I am also using this only... its working well..

Upvotes: 1

Related Questions