Login cannot redirect to another page

Donald Symmons 941 Reputation points
2023-01-13T16:06:10.11+00:00

I recently tried to use authentication and authorization on my login, but when I click to login nothing happens; it does not redirect

here is my code

Login.aspx.cs

 private bool ValidateUser(string email, string pass)
        {
            SqlConnection conn;
            SqlCommand cmd;
            string lookupPassword = null;

            // Check for invalid userName.
            // userName must not be null and must be between 1 and 15 characters.
            if ((null == email) || (0 == email.Length) || (email.Length > 15))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                return false;
            }

            // Check for invalid passWord.
            // passWord must not be null and must be between 1 and 25 characters.
            if ((null == pass) || (0 == pass.Length) || (pass.Length > 25))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                return false;
            }

            try
            {
                // Consult with your SQL Server administrator for an appropriate connection
                // string to use to connect to your local SQL Server.
                conn = new SqlConnection("Data Source=(LocalDB)
                conn.Open();

                // Create SqlCommand to select pwd field from users table given supplied userName.
                cmd = new SqlCommand("Select pass from Users where email=@email", conn);
                cmd.Parameters.Add("@email", SqlDbType.NVarChar, 25);
                cmd.Parameters["@email"].Value = email;

                // Execute command and fetch pwd field into lookupPassword string.
                lookupPassword = (string)cmd.ExecuteScalar();

                // Cleanup command and connection objects.
                cmd.Dispose();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                // Add error handling here for debugging.
                // This error message should not be sent back to the caller.
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
            }

            // If no password found, return false.
            if (null == lookupPassword)
            {
                // You could write failed login attempts here to event log for additional security.
                return false;
            }

            // Compare lookupPassword and input passWord, using a case-sensitive comparison.
            return (0 == string.Compare(lookupPassword, pass, false));
        }

        private void CmdLogin_ServerClick(object sender, System.EventArgs e)
        {
            if (ValidateUser(txtUserName.Value, (txtUserPass.Value)))
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, chkPersistCookie.Checked);
            else
                Response.Redirect("Login.aspx", true);
        }

Login.aspx


                    
                    
                    
                       <asp:Label ID="lblMsg" ForeColor="red" Font-Size="10" runat="server" />
                    
                    <label for="txtUsername" style="font-weight: 500;">Email</label>
                    <input id="txtUserName" type="text" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Email Address"/>
                     <asp:RequiredFieldValidator ControlToValidate="txtUserName" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserName" />
                    
                    <label for="txtPassword" style="font-weight: 500;">Password</label>
                    <input id="txtUserPass" type="password" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Password"/>
                    <asp:RequiredFieldValidator ControlToValidate="txtUserPass" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserPass" />
                    
                    
                    Remember me: <asp:CheckBox ID="chkPersistCookie" runat="server" AutoPostBack="false" />
                    
                    <input type="submit" value="Login" runat="server" class="btn btn-primary" id="CmdLogin" style="background-color: #32657c;" />
                
ASP.NET Web Forms
ASP.NET Web Forms
A part of the ASP.NET web application framework that can be used to create ASP.NET web applications.
403 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,983 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
1,211 questions
{count} votes

Accepted answer
  1. QiYou-MSFT 851 Reputation points Microsoft Employee
    2023-01-17T07:32:16.2933333+00:00

    Hi @Donald Symmons

    Your problem should be that Server_Click command is not right.

    Add in Page_Load:

    protected void Page_Load(object sender, EventArgs e)
            {
                cmdLogin.ServerClick += new EventHandler(cmdLogin_ServerClick);
            }
    

    Here is my code

    Logon.aspx.cs

    Logon.aspx

    Default.aspx.cs

    Default.aspx

     public partial class Logon : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                cmdLogin.ServerClick += new EventHandler(cmdLogin_ServerClick);
            }
            private bool ValidateUser(string userName, string passWord)
            {
                SqlConnection conn;
                SqlCommand cmd;
                string lookupPassword = null;
                // Check for invalid userName.
                // userName must not be null and must be between 1 and 15 characters.
                if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
                {
                    System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                    return false;
                }
                // Check for invalid passWord.
                // passWord must not be null and must be between 1 and 25 characters.
                if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
                {
                    System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                    return false;
                }
                try
                {
                    // Consult with your SQL Server administrator for an appropriate connection
                    // string to use to connect to your local SQL Server.
                    conn = new SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs");
                    conn.Open();
                    // Create SqlCommand to select pwd field from users table given supplied userName.
                    cmd = new SqlCommand("Select pwd from users where uname=@userName", conn);
                    cmd.Parameters.Add("@userName", SqlDbType.VarChar, 25);
                    cmd.Parameters["@userName"].Value = userName;
                    // Execute command and fetch pwd field into lookupPassword string.
                    lookupPassword = (string)cmd.ExecuteScalar();
                    // Cleanup command and connection objects.
                    cmd.Dispose();
                    conn.Dispose();
                }
                catch (Exception ex)
                {
                    // Add error handling here for debugging.
                    // This error message should not be sent back to the caller.
                    System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
                }
                // If no password found, return false.
                if (null == lookupPassword)
                {
                    // You could write failed login attempts here to event log for additional security.
                    return false;
                }
                // Compare lookupPassword and input passWord, using a case-sensitive comparison.
                return (0 == string.Compare(lookupPassword, passWord, false));
            }
            private void cmdLogin_ServerClick(object sender, System.EventArgs e)
            {
                if (ValidateUser(txtUserName.Value, txtUserPass.Value))
                {
                    FormsAuthenticationTicket tkt;
                    string cookiestr;
                    HttpCookie ck;
                    tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
                    DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
                    cookiestr = FormsAuthentication.Encrypt(tkt);
                    ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                    if (chkPersistCookie.Checked)
                        ck.Expires = tkt.Expiration;
                    ck.Path = FormsAuthentication.FormsCookiePath;
                    Response.Cookies.Add(ck);
                    string strRedirect;
                    strRedirect = Request["ReturnUrl"];
                    if (strRedirect == null)
                        strRedirect = "default.aspx";
                    Response.Redirect(strRedirect, true);
                }
                else
                    Response.Redirect("logon.aspx", true);
            }
        }
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Logon.aspx.cs" Inherits="Test1_17.Logon"  %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <h3>
        <font face="Verdana">Logon Page</font>
    </h3>
    <table>
        <tr>
            <td>Email:</td>
            <td><input id="txtUserName" type="text" runat="server"/></td>
            <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
                Display="Static" ErrorMessage="*" runat="server" 
                ID="vUserName" /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input id="txtUserPass" type="password" runat="server"/></td>
            <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
            Display="Static" ErrorMessage="*" runat="server"
            ID="vUserPass" />
            </td>
        </tr>
        <tr>
            <td>Persistent Cookie:</td>
            <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>
            <td></td>
        </tr>
    </table>
    <input type="submit" Value="Logon" runat="server" ID="cmdLogin" /><p></p>
    <asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />
        </form>
    </body>
    </html>
    
    protected void Page_Load(object sender, EventArgs e)
            {
                cmdSignOut.ServerClick += new EventHandler(cmdSignOut_ServerClick);
            }
            private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
            {
                FormsAuthentication.SignOut();
                Response.Redirect("logon.aspx", true);
            }
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test1_17.Default" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
          <input type="submit" Value="SignOut" runat="server" id="cmdSignOut"/>
        </form>
    </body>
    </html>
    

    TestBack

    Best Regards

    Qi You


2 additional answers

Sort by: Most helpful
  1. Jose Zero 486 Reputation points
    2023-01-14T12:32:18.7066667+00:00

    The RedirectFromLoginPage method redirects to the return URL specified in the query string using the ReturnURL variable name. If the ReturnURL variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.

    Sounds you missed set DefaultUrl in web.config.
    As an example:

    <authentication mode="Forms">
      <forms loginUrl="member_login.aspx"
        defaultUrl="index.aspx" />
    </authentication>
    

  2. QiYou-MSFT 851 Reputation points Microsoft Employee
    2023-01-16T08:34:38.6166667+00:00

    Hi @Donald Symmons

    First of all, if you use input as an input control, the way our backend gets the data is:

    string username=Request[txtUserName];
    

    Then we're comparing it to the data you get in your database.

    We can use this method to implement redirection.

    Response.Redirect("");
    

    But here I suggest you use asp:TextBox as an input control, because it is more convenient.

    Here is my example:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
           <table>
            <tr>
                <td> <asp:Label ID="Label1" runat="server" Text="UserName:"></asp:Label> </td>
                <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
            </tr>
              <tr>
                <td> <asp:Label ID="Label2" runat="server" Text="PassWord:" ></asp:Label> </td>
                <td> <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox></td>
            </tr>
             <tr>
                
                <td> <asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" /> </asp:TextBox></td>
            </tr>
           </table>
        </div>
        </form>
    </body>
    </html>
    
    
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class About : Page
        {
    
    
            protected void Page_Load(object sender, EventArgs e)
            {
    
    
                
            }
           
            protected void Button1_Click(object sender, EventArgs e)
            {
    
                string username = TextBox1.Text;
                string password = TextBox2.Text;
                if (username != null || password != null)
                {
                    if (username == "1234" && password == "1234")
                    {
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        Response.Write("Fail");
                    }
                }
            }
    
    
        }
    }
    

    </body>

    }TestPassword

    Best Regards

    Qi You