Search code examples
c#asp.netwebformsforms-authenticationmembership-provider

Avoid manual setting of FormsAuthentication cookie


I have been have bad behavior at different times using this:

FormsAuthentication.SetAuthCookie(user.UserName, true);

How does/will .Net set the cookie otherwise?

I have tried this: (System.Web.HttpContext.Current.User.Identity.IsAuthenticated fails sometimes)

But my User.Identity.IsAuthenticated is always false

What gives?


Solution

  • First make sure that forms authentication is enabled in your web config file.

    <authentication mode="Forms" />
    

    Use code like below to make it work. The method RedirectFromLoginPage will create the authentication cookie as well as redirect the user to the original page or the default URL i.e. home page.

    if (Membership.ValidateUser(userName, password))//or whatever method you use
     {
        // Log the user into the site
        FormsAuthentication.RedirectFromLoginPage(userName, false);
     }