ASP.NET Membership: how to set the user as logged in

marcgg picture marcgg · May 26, 2009 · Viewed 76.4k times · Source

I am trying to get the Membership Provider to work.

So far I have:

 <asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
 </asp:Login>

calling :

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        Response.Redirect("/admin/default.aspx");
        // Set the user as logged in?
    }
}

If I enter the correct login/password, the ValidateUser function returns true. So my question is: how do I set the user as logged in?

I am testing this in my pages doing :

protected void Page_Load(object sender, EventArgs e)
{
    if ( Membership.GetUser()==null)
    {
        Response.Redirect("/admin/login.aspx");
    }
    // else "you are logged in, congratulations"                
}

I would have used the default functions, but it is just not working and a google search made me think that I will save time by actually recoding all that myself.

Anything will help!

EDIT: Regarding the accepted answer, it is the correct one for "how to set the user as logged in" and works fine. It didn't fixed my specific problem but only a part of it. Thought if you look thought the comments you will find interesting pointers.

EDIT 2 and solution: Ok I finally worked it out thanks to all the comments. Here is what I did, it's simpler than what I expected :

Page that checks login state:

 protected void Page_Load(object sender, EventArgs e)
 {
     if ( !Request.IsAuthenticated)
     {
         Response.Redirect("/admin/login.aspx");
     }  

Log out:

   protected void LoginStatus1_Logout(object sender, LoginCancelEventArgs e)
   {
       FormsAuthentication.SignOut();
       Response.Redirect("/admin/login.aspx");
   }
}

web.config:

<authentication mode="Forms" />

login:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        FormsAuthentication.SetAuthCookie(Login1.UserName, true);
        Response.Redirect("/admin/default.aspx");

    }
}

Answer

Gromer picture Gromer · May 26, 2009

Put this in Login1_Authenticate before calling Response.Redirect("/admin/default.aspx");

FormsAuthentication.SetAuthCookie("username", true);