Search code examples
c#asp.netsessionmaster-pages

Restrict user access using session - ASP.NET


I am new to programming. I have developed a web application, on login page I am capturing the session id if the login is successful and redirect the user to the home page.

My query - Is it possible to restrict users from accessing web pages based on their role by using the session control in the master page. If so, how to hide certain web pages?

Login page code -

con.Open();
SqlCommand cmd = new SqlCommand("select * from LoginDB where (EmpCode COLLATE Latin1_General_CS_AS = @EmpCode) and (Password COLLATE Latin1_General_CS_AS =@Password)", con);
cmd.Parameters.AddWithValue("@EmpCode", txtLogin.Text.Trim());
cmd.Parameters.AddWithValue("@Password", txtPwd.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    var userRow = dt.Rows[0];
    Session["idname"] = userRow["Name"].ToString();
    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + "Login Success!" + "')</script>");
    Session["identity"] = txtLogin.Text;
    Response.Redirect("Mainpage.aspx", false);
}
else
{
    txtLogin.Text = "";
    ShowMessage("UserId / Password is Not Correct!");
}
con.Close();

Code to be used in master page,

protected void Page_Load(object sender, EventArgs e)
{
   string mnm = Session["identity"].ToString();
   if (mnm == "NormalUser")
   {
       //Hide certain web pages like Asset.aspx web page
   }       
}

Solution

  • I suggest you that check roles of user in Page.OnInit for each aspx you have instead of doing that in master page. For example in Asset.aspx.cs you can do that as follows:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    
        string mnm = Session["identity"].ToString();
        if (mnm != "NormalUser")//check whatever you want with the identity
        {
            throw new UnauthorizedAccessException("You are not allowed to view this page");
        }  
    }
    

    So that you can apply this approach for other pages.