librariman
librariman

Reputation: 121

.Net Forms Authentication Authentication doesn't stick

I'm having difficulty sending a user from a login page to a page requiring authentication. The user is authenticated on the first page but after the authentication check on the second page, gets sent right back to login. Here's the gist of the code...

Page-Requiring-Authentication:

protected void Page_Load(object sender, EventArgs e)
{
    /*Make sure the user is authenticated.  If not, redirect them to the Login page*/
    if (!HttpContext.Current.Request.IsAuthenticated)

    else
        LabelMsg.Text = "User: " + System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.ToString();
} //end Page_Load()

Here's the gist of the login code:

if (GridViewBookList.Rows.Count > 0)
{
    string[] roles = new string[] { "admin", "newbooks" };
    HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(TextBoxUser.Text), roles);
    FormsAuthentication.SetAuthCookie("admin", true);
    FormsAuthentication.RedirectFromLoginPage(TextBoxUser.Text, true);
}
else
{
    LabelMsg.Text = "Incorrect username or password";

If anyone could be of any assistance, it would be greatly appreciated.

Upvotes: 0

Views: 44

Answers (1)

Tchaps
Tchaps

Reputation: 874

Your login should look like this :

 private void Login_Click(Object sender, EventArgs e)
 {
     // Create a custom FormsAuthenticationTicket containing
     // application specific data for the user.

     string username     = UserNameTextBox.Text;
     string password     = UserPassTextBox.Text;
     bool   isPersistent = false;

    if (Membership.ValidateUser(username, password))
    {
    string userData = "ApplicationSpecific data for this user.";

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
       username,
       DateTime.Now,
       DateTime.Now.AddMinutes(30),
       isPersistent,
       userData,
       FormsAuthentication.FormsCookiePath);

      // Encrypt the ticket.
     string encTicket = FormsAuthentication.Encrypt(ticket);

      // Create the cookie.
      Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

      // Redirect back to original URL.
      Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
     }
     else
        {
       Msg.Text = "Login failed. Please check your user name and password and try again.";
        }
}

check this page FormsAuthentication.GetRedirectUrl Method

Upvotes: 1

Related Questions