Admin does not redirect after login

Last Reply 3 days ago By dharmendr

Posted 7 days ago

The issue I am facing right now is that Admin does not redirect after login. Other users can successfully redirect to user’s page after login but Admin can’t redirect, after login the textboxes in the login form just clears its data.

Here is how my whole login scenario goes:

After login, it is supposed to redirect according to Roles. Super Admin and Admin will be redirected to Admin page, while Super User and User will be redirected to Users page.

Currently when Admin clicks on the login button, it does nothing. But when Super User and User clicks on the login button, it redirects them to Users page.

I will walk you through what I have done.

This is my login code:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (this.Page.User.Identity.IsAuthenticated)
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/Login.aspx");
                }
            }
        }

        protected void ValidateUser(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textUser.Text) & !string.IsNullOrEmpty(txtPassword.Text))
            {
                string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT Id, RoleId FROM Users WHERE email = @email AND pass = @pass", con))
                    {
                        con.Open();
                        cmd.Parameters.AddWithValue("@email", textUser.Text.Trim());
                        cmd.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
                        //string Id = Convert.ToString(cmd.ExecuteScalar());
                        SqlDataReader sdr = cmd.ExecuteReader();
                        string Id = string.Empty, RoleId = string.Empty;
                        if (sdr.Read())
                        {
                            Id = Convert.ToString(sdr["Id"]);
                            RoleId = Convert.ToString(sdr["RoleId"]);
                        }
                        con.Close();

                        if (!string.IsNullOrEmpty(Id))
                        {
                            string users = "";
                            using (SqlCommand cmd1 = new SqlCommand("SELECT Id FROM UserActivation WHERE Id = @Id"))
                            {
                                cmd1.CommandType = CommandType.Text;
                                cmd1.Parameters.AddWithValue("@Id", Id);
                                cmd1.Connection = con;
                                con.Open();
                                users = Convert.ToString(cmd1.ExecuteScalar());
                                con.Close();
                            }
                            if (string.IsNullOrEmpty(users))
                            {
                                int user = 0;
                                using (SqlCommand cmd2 = new SqlCommand("SELECT Id FROM Users WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass"))
                                {
                                    cmd2.CommandType = CommandType.Text;
                                    cmd2.Parameters.AddWithValue("@email", textUser.Text.Trim());
                                    cmd2.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
                                    cmd2.Connection = con;
                                    con.Open();
                                    user = Convert.ToInt32(cmd2.ExecuteScalar());
                                    con.Close();
                                }
                                if (user > 0)
                                {
                                    Session["user"] = Id;
                                    con.Open();
                                    string query = "SELECT LastLogin, IsActive from Users WHERE Id = @Id";
                                    using (SqlCommand cmd3 = new SqlCommand(query, con))
                                    {
                                        cmd3.Parameters.AddWithValue("@Id", Session["user"]);
                                        Session["LastLogin"] = Convert.ToDateTime(cmd3.ExecuteScalar());

                                    }
                                    string UpdateLog = @"UPDATE Users SET LastLogin=@dateandtime, IsActive=@IsActive WHERE Id = @Id";
                                    using (SqlCommand cmd4 = new SqlCommand(UpdateLog, con))
                                    {
                                        cmd4.Parameters.AddWithValue("@dateandtime", DateTime.UtcNow);
                                        cmd4.Parameters.AddWithValue("@IsActive", "1");
                                        cmd4.Parameters.AddWithValue("@Id", Session["user"]);
                                        cmd4.ExecuteNonQuery();
                                    }
                                    con.Close();
                                }
                                SqlCommand cmd5 = new SqlCommand("SELECT RoleName From [RoleTable] WHERE RoleId = @RoleId", con);
                                cmd5.Parameters.AddWithValue("@RoleId", RoleId);
                                DataTable dt = new DataTable();
                                SqlDataAdapter sda = new SqlDataAdapter(cmd5);
                                sda.Fill(dt);
                                if (dt.Rows.Count > 0)
                                {
                                    string roles = dt.Rows[0]["RoleName"].ToString().Trim().ToLower();
                                    if (roles == "SuperAdmin")
                                    {
                                        Session["user"] = Id;
                                        FormsAuthentication.RedirectFromLoginPage(Id, true);
                                        Response.Redirect("~/AdminPage.aspx");
                                    }
                                    else if (roles == "Admin")
                                    {
                                        Session["user"] = Id;
                                        FormsAuthentication.RedirectFromLoginPage(Id, true);
                                        Response.Redirect("~/AdminPage.aspx");
                                    }
                                    else if (roles == "SuperUser")
                                    {
                                        Session["user"] = Id;
                                        FormsAuthentication.RedirectFromLoginPage(Id, true);
                                        Response.Redirect("~/UsersPage.aspx");
                                    }
                                    else if (roles == "User")
                                    {
                                        Session["user"] = Id;
                                        FormsAuthentication.RedirectFromLoginPage(Id, true);
                                        Response.Redirect("~/UsersPage.aspx");
                                    }
                                    else
                                    {
                                        Response.Redirect("~/Login.aspx");
                                    }
                                }
                            }
                            else
                            {
                                dvMessage.Visible = true;
                                lblMessage.Visible = true;
                                lblMessage.ForeColor = System.Drawing.Color.Red;
                                lblMessage.Text = "Account has not been activated";
                                txtPassword.Text = "";
                                txtPassword.Focus();
                            }
                        }
                        else
                        {
                            dvMessage.Visible = true;
                            lblMessage.Visible = true;
                            lblMessage.ForeColor = System.Drawing.Color.Red;
                            lblMessage.Text = "Invalid Login Details";
                            txtPassword.Text = "";
                            txtPassword.Focus();
                        }
                    }
                }
            }
            else
            {
                dvMessage.Visible = true;
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "All Fields are Required";
            }
        }

I created a folder called AdminFolder, then I added the AdminPag.aspx and web.config file inside the folder.

Here is the web.config file in the AdminFolder

<location path="AdminFolder">
  <system.web>
    <authentication mode="Forms">
      <forms cookieless="UseCookies" defaultUrl="~/AdminPage.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880" />
    </authentication>
    <authorization>
      <allow roles="TopAdmin"/>
      <deny users="?"/>
    </authorization>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
</location>

There is also a web.config file in the root directory

 <system.web>
    <authentication mode="Forms">
      <forms cookieless="UseCookies" defaultUrl="~/UsersPage.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880" />
    </authentication>
    <authorization>
      <deny users ="?" />
    </authorization>
    <siteMap enabled ="true" defaultProvider="SiteMap">
      <providers>
        <add name="SiteMap" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web.sitemap" securityTrimmingEnabled="true" />
      </providers>
    </siteMap>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>

Then I added this code in the Application_Authenticate evet of the Global.asax file

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity id)
                    {
                        FormsAuthenticationTicket ticket = id.Ticket;
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                }
            }
        }

I also added a sitemap to the project

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="" title="Manager"  description="" roles="*">
    <siteMapNode url="~/Manager.aspx" title="Manager"  description="Home Page" roles="*" />
  <siteMapNode url="javascript:;" title="TopAdmin" description="Admin Page" roles ="TopAdmin">
    <siteMapNode url ="~/Admin/QuirverManagement.aspx" title="Admin" description="AdminPage"></siteMapNode>
  </siteMapNode>
  <siteMapNode url="~/Overview.aspx" title="UsersPage" description="User Home Page" roles="*" />
  </siteMapNode>
</siteMap>
You are viewing reply posted by: PrinceG 6 days ago.
Posted 6 days ago

It will take little time, I will get back to you tommorrow