Role based Folder (Directory) access in ASP.Net

RichardSa
 
on Jan 20, 2023 05:35 AM
651 Views

I have every page that belongs to administrator inside AdminFolder and other pages in the root directory, then after putting this XML code in the web.config file. I signed in in as a Top Admin and then copied the page address in the address tab. I logged out. I later logged in as user and when I was logged in as a user, I pasted the Admin page address in the browser tab and to my surprise, the admin page showed. I thought that it was going to redirect me and show error message I am not Admin and that I should log in as Admin.

How do I solve this please?

<location path="AdminFolder">
    <system.web>
      <authorization>
        <allow roles="TopAdmin, admin"/>
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

  <location path="Signup.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

  <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
PrinceG
 
on Jan 20, 2023 05:57 AM
on Jan 20, 2023 06:16 AM

Hi RichardSa,

Please refer below sample and above updated code.

HTML

Login

<div class="row">
    <div class="col-sm-5">
        <div class="container-fluid">
            <br />
            <h2 class="form-signin-heading">LOGIN</h2>
            <div id="dvMessage" runat="server" visible="false" class="alert alert-danger">
                <strong><i class="fad fa-exclamation-square" aria-hidden="true"></i>&nbsp;</strong>
                <asp:Label ID="lblMessage" runat="server" />
            </div>
            <label for="txtUsername">UserName</label>
            <asp:TextBox ID="txtUsername" runat="server" CssClass="form-control" Font-Size="11pt" placeholder="UserName" Width="30%" /><br />
            <br />
            <label for="txtPassword">Password</label>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form-control" Font-Size="11pt" placeholder="Password" /><br />
            <a href="#">Forgotten Password?</a>
            <br />
            <br />
            <asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" BackColor="#32657c" Text="Login" OnClick="ValidateUser" />
            <br />
            <br />
        </div>
        <br />
    </div>
</div>

AdminPage

<h1>Admin View Only</h1>

Home

<h1>Home</h1>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<hr />
<asp:LinkButton ID="lnkLogout" runat="server" Text="Logout" Font-Size="11pt" ForeColor="red" OnCommand="Logout_Command"></asp:LinkButton>

Web.Config

Write this inside system.web tag.

<authentication mode="Forms">
	<forms cookieless="UseCookies" defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
<authorization>
	<allow roles="SuperAdmin, Admin"/>
	<deny users="?"/>
</authorization>

Namespaces

Login

using System.Data;
using System.Web.Security;
using System.Configuration;
using System.Data.SqlClient;

Home

using System.Web.Security;

Code

Login

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {

        // if they came to the page directly, ReturnUrl will be null.
        if (String.IsNullOrEmpty(Request["ReturnUrl"]))
        {
            /* in that case, instead of redirecting, I hide the login
                controls and instead display a message saying that are
                already logged in. */
        }
        else
        {
            Response.Redirect("~/Login.aspx");
        }
    }
}

protected void ValidateUser(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtUsername.Text) & !string.IsNullOrEmpty(txtPassword.Text))
    {
        string connectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT UserId FROM User_Login WHERE Email = @Email AND Password = @Password", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@Email", txtUsername.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                string Id = Convert.ToString(cmd.ExecuteScalar());
                con.Close();

                if (!string.IsNullOrEmpty(Id))
                {
                    string User_Login = "";
                    using (SqlCommand cmd1 = new SqlCommand("SELECT UserId FROM User_Login WHERE UserId = @UserId"))
                    {
                        cmd1.CommandType = CommandType.Text;
                        cmd1.Parameters.AddWithValue("@UserId", Id);
                        cmd1.Connection = con;
                        con.Open();
                        User_Login = Convert.ToString(cmd1.ExecuteScalar());
                        con.Close();
                    }
                    if (!string.IsNullOrEmpty(User_Login))
                    {
                        int user = 0;
                        using (SqlCommand cmd2 = new SqlCommand("SELECT UserId FROM User_Login WHERE Password = @Password AND Email = @Email AND Password = @Password"))
                        {
                            cmd2.CommandType = CommandType.Text;
                            cmd2.Parameters.AddWithValue("@Email", txtUsername.Text.Trim());
                            cmd2.Parameters.AddWithValue("@Password", 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 User_Login WHERE UserId = @UserId";
                            using (SqlCommand cmd3 = new SqlCommand(query, con))
                            {
                                cmd3.Parameters.AddWithValue("@UserId", Session["user"]);
                                Session["LastLogin"] = Convert.ToDateTime(cmd3.ExecuteScalar());
                            }
                            string UpdateLog = @"UPDATE User_Login SET LastLogin=@dateandtime, IsActive=@IsActive WHERE UserId = @UserId";
                            using (SqlCommand cmd4 = new SqlCommand(UpdateLog, con))
                            {
                                cmd4.Parameters.AddWithValue("@dateandtime", DateTime.UtcNow);
                                cmd4.Parameters.AddWithValue("@IsActive", "1");
                                cmd4.Parameters.AddWithValue("@UserId", Session["user"]);
                                cmd4.ExecuteNonQuery();
                            }
                            con.Close();
                        }

                        SqlCommand cmd5 = new SqlCommand("SELECT RoleName From [RoleTable] WHERE RoleId = @RoleId",con);
                        cmd5.Parameters.AddWithValue("@RoleId", Id);
                        DataTable dt = new DataTable();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd5);
                        sda.Fill(dt);
                        if (dt.Rows.Count > 0)
                        {
                            string role = dt.Rows[0]["RoleName"].ToString().Trim().ToLower();
                            if (role == "superadmin")
                            {
                                Session["user"] = Id;
                                FormsAuthentication.RedirectFromLoginPage(Id, true);
                                    Response.Redirect("~/AdminFolder/AdminPage.aspx");
                            }
                            else if (role == "admin")
                            {
                                Session["user"] = Id;
                                FormsAuthentication.RedirectFromLoginPage(Id, true);
                                Response.Redirect("~/AdminFolder/AdminPage.aspx");
                            }
                            else if (role == "superuser")
                            {
                                Session["user"] = Id;
                                FormsAuthentication.RedirectFromLoginPage(Id, true);
                                Response.Redirect("~/Home.aspx");
                            }
                            else if (role == "user")
                            {
                                Session["user"] = Id;
                                FormsAuthentication.RedirectFromLoginPage(Id, true);
                                Response.Redirect("~/Home.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";
    }
}

Home

protected void Page_Load(object sender, EventArgs e)
{
    if (this.Page.User.Identity.IsAuthenticated)
    {
        lblMessage.Text = "Welcome:" + Session["user"].ToString();
    }
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
    Response.Cache.SetNoStore();
    Response.AppendHeader("Pragma", "no-cache");
}

protected void Logout_Command(Object sender, CommandEventArgs e)
{
    if (this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.SignOut();
        Session.Abandon();
        FormsAuthentication.RedirectToLoginPage();
    }
}

Screenshot