views:

2367

answers:

3

I have a login page that uses ASP.NET membership. Once I've validated the user I need to store some details about them in Session variables. The problem is that

Membership.GetUser() == null and 
User.Identity.IsAuthenticated == false

until I have navigated away from the page.

I have tried using

FormsAuthentication.Authenticate(tbUsername.Text, tbPassword.Text);

And checking User.Identity.IsAuthenticated but it's returning false until I reach another page. Any suggestions?

+3  A: 

Well, FormsAuthentication.Authenticate() returns a boolean, so you will know whether or not authentication was successful. If it was, you can pass the user's username to Membership.GetUser() and access the returned MembershipUser object to grab whatever data you need and store it in the session.

if (FormsAuthentication.Authenticate(tbUsername.Text, tbUsername.Text)) {
   MembershipUser user = Membership.GetUser(tbUsername.Text);
   // Set session variables here.
   FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, rememberMe.Checked);
}
Jon Freeland
A: 

If you're not using the Login control, have you tried calling FormsAuthentication.RedirectFromLoginPage( authorizedUserName, createPersistantCookie); and checking after that?

If you are using the Login control, there's probably an event on the control you can handle to get the data you need, such as LoggedIn

Greg
A: 

Depends on how your doing it but if you are NOT using the ASP Login control and you are doing the auth yourself you need to set the AuthCookie like this...

string userName = UserName.Text;
string password = Password.Text;

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

   MembershipUser user = Membership.GetUser();

   if(user != null){
      // success
   }
   else{
      // failed
   }
}
gmcalab