Execute ASP.NET Membership Login from codebehind in button click handler

ChessWhiz picture ChessWhiz · Oct 26, 2010 · Viewed 8.4k times · Source

I'm trying to seamlessly log in the user without prompting for credentials as part of a <asp:Wizard> process. My strategy is to handle the NextButtonClick event and login the user in code. I already have the user's credentials saved in session variables.

Is it possible to login a user in code? Will a hidden <asp:Login> control behind the scenes be required?

Answer

Jack Marchetti picture Jack Marchetti · Oct 26, 2010

If you're storing their credentials in session, I hope you are encrypting them.

But yes, if you have their credentials already, you can do:

FormsAuthentication.SetAuthCookie(username, true);

You can also run:

if(Membership.ValidateUser(username, password)) {
     FormsAuthentication.SetAuthCookie(username, true);
}

before hand to make sure that you have the correct username and password.