Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect After Login : Web.config

In my ASP.NET Web Application, the project structure is shown by the following image:

enter image description here

The Web.config of the Site has form authentication:

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" />      
</authentication>

And the Web.config of the Pages folder has:

<?xml version="1.0"?>
<configuration>
<system.web>
  <authorization>
    <allow roles="Admin"/>
    <deny users="*"/>
  </authorization>
</system.web>

I have an User admin with role Admin. After successful Login I am trying to redirect the user in Home.aspx resides in the Pages folder as:

protected void EMSLogin_Authenticate(object sender, AuthenticateEventArgs e) {
    TextBox UserNameTextBox = EMSLogin.FindControl("UserName") as TextBox;
    TextBox PasswordTextBox = EMSLogin.FindControl("Password") as TextBox;

    if (Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text)) {
    Response.Redirect("~/Pages/Home.aspx");
    }
}

But it is not working. It is again redirecting to the Login page i.e., Login.aspx with the URL: localhost:3695/Login.aspx?ReturnUrl=%2fPages%2fHome.aspx.

How can I achieve this? Any information will be very helpful.

Regards.

like image 246
Tapas Bose Avatar asked Mar 18 '12 13:03

Tapas Bose


1 Answers

Membership.ValidateUser only validates the username and password against the membership provider. It doesn't emit the authentication cookie.

If you want to do this you need to use the SetAuthCookie method before redirecting:

if (Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text)) 
{
    FormsAuthentication.SetAuthCookie(UserNameTextBox.Text, false);
    Response.Redirect("~/Pages/Home.aspx");
}

or if in your web.config you set:

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" defaultUrl="~/Pages/Home.aspx" timeout="2880" />
</authentication>

you could also use the RedirectFromLoginPage method which will emit the authentication cookie and redirect you to the default page:

if (Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text)) 
{
    FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text, false);
}
like image 67
Darin Dimitrov Avatar answered Sep 24 '22 14:09

Darin Dimitrov