Resources » Code Snippets » ASP.NET WebForms

How to restrict user access in ASP.NET website using ASP.NET Menu ?


Posted Date: 19-Feb-2012  Last Updated:   Category: ASP.NET WebForms    
Author: Member Level: Diamond    Points: 30


In this article I have explained about how to restrict use access in the ASP.NET website. For example if user is admin it enable to access all the pages otherwise non admin user protect to view other pages in this example I explained in detail about that concept



Description:
Initially I have designed login page to verify user authentication

Screen shot

Server Side

protected void Button1_Click(object sender, EventArgs e)
{
try
{
sqlcon.Open();
//Check Enter username and password match with database value default i store username "ravi" and password "test123"
sqlcmd = new SqlCommand("select * from userLogin where usrname='" + TextBox1.Text + "' and pwd='" + TextBox2.Text + "'", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
/*If user entered detailed match then exection come into this block we need to assign user name in Session
because we can access the session value in any other page in the same web site*/
Session["loginuser"] = TextBox1.Text;
//Afetr Assign session value redirect to home page
Response.Redirect("Default2.aspx");
}
else
{
TextBox1.Text = "";
TextBox2.Text = "";
Page.RegisterClientScriptBlock("Alert Message", "<script type='text/javascript'>alert('Invalid Login Details!')</script>");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlcon.Close();
}
}

I have create ASP.NET Menu control like this

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Menu.ascx.cs" Inherits="Menu" %>

<%--IE8 Issue fix code--%>
<style type="text/css">
.IE8Fix{z-index: 1000;}
</style>

<%--Below line is static header menu --%>
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" Width="400" StaticEnableDefaultPopOutImage="false"
BackColor="#B9014A" OnMenuItemClick="Menu1_MenuItemClick">

<%--To Set Font Style, Border color, Border with extra of your static menuitem (Top menu row) in below line--%>
<StaticMenuItemStyle Font-Names="Arial black" Font-Size="10px" Height="30px" ForeColor="#ffffff" />

<%--To Set Top menu row handover style in below line--%>
<%--<StaticHoverStyle BackColor="#023178" ForeColor="#ffffff" />--%>

<%--To Set Font Style, Border color, Border with extra of your Dynamic menuitem (drop down menu) in below line--%>
<DynamicMenuItemStyle Font-Names="Arial black" Font-Size="10px" HorizontalPadding="5px"
VerticalPadding="2px" Height="25px" BackColor="#955870" ForeColor="White"
Font-Bold="False"
Width="200" />

<DynamicMenuStyle BackColor="#1D3F6C" ForeColor="White" CssClass="IE8Fix"/>


<%--To set Drop down menu item handover style in below line--%>
<DynamicHoverStyle BackColor="#FFFFFF" ForeColor="#040818" Width="100%" />

<%--Specify below what are the menu show in menu control--%>
<Items>
<asp:MenuItem Text="File" Value="File">
<asp:MenuItem Text="New" Value="New" Enabled="false"></asp:MenuItem>
<asp:MenuItem Text="Open" Value="Open" Enabled="false"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Edit" Value="Edit">
<asp:MenuItem Text="Copy" Value="Copy" Enabled="false"></asp:MenuItem>
<asp:MenuItem Text="Paste" Value="Paste" Enabled="false"></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>


Menu Control server side code

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class Menu : System.Web.UI.UserControl
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Get waht are the access pages for login user using session value
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("select * from usrrestrict where uid='" + Session["loginuser"].ToString() + "'",sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
string accpage = "";

if (dt.Rows.Count > 0)
{
Session.Remove("accpage");
//Enble true of each page from the usrrestrict table
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{

dr = dt.Rows[i];
accpage += dr["accpage"].ToString() + ",";
switch (dr["accpage"].ToString())
{
case "New":
Menu1.Items[0].ChildItems[0].Enabled = true;
break;
case "Open":
Menu1.Items[0].ChildItems[1].Enabled = true;
break;
case "Copy":
Menu1.Items[1].ChildItems[0].Enabled = true;
break;
case "Paste":
Menu1.Items[1].ChildItems[1].Enabled = true;
break;
}
}
//Finally Stored it lmited access pages name in the Session because we use this session in each to protect user directly enter url
Session["accpage"] = accpage;
}


}
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{

if (e.Item.Depth.ToString() == "0")
{
return;
}

switch (e.Item.Value.ToString())
{
case "New":
Response.Redirect("New.aspx");
break;
case "Open":
Response.Redirect("Open.aspx");
break;
case "Copy":
Response.Redirect("Copy.aspx");
break;
case "Paste":
Response.Redirect("Paste.aspx");
break;
}

}
}

That's all here after your ASP.NET Menu automatically enable true or false using database value

Output look like this
Screen shot

Suppose user directly typed not accessible page in that url I protect use this way

protected void Page_Load(object sender, EventArgs e)
{
Boolean pacess=false;
if (Session["accpage"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string[] acright;
acright=Session["accpage"].ToString().Split(',');
foreach (string s in acright)
{
//Mention below your current page name
if (s == "New")
{
pacess = true;
break;
}
}
}

//Check user have rights to access this page
if (pacess == false)
{
Response.Redirect("Default.aspx");
}
}

Unauthorized page error shows like this
Screen shot

Source Code Detail:
Here with I have attached entire source code download it and try to learn ASP.NET Menu restriction.
Front End : ASP.NET
Code Behind : C#

Conclusion:
I hope this article help to know about ASP.NET Menu restriction.


Did you like this resource? Share it with your friends and show your love!

Responses to "How to restrict user access in ASP.NET website using ASP.NET Menu ?"
Guest Author: Rahul     28 Mar 2012
All is wellllllllllllllllllllll.
wow, u provide a nice service.



Author: nuwan rathnayake    11 Aug 2012Member Level: Silver   Points : 0
Work Great.. well done.
My idea is this is application is best. If you can do this using sql parameters. because this can affected sql injection attack.



Guest Author: Pho Chit     05 Jul 2013
I used your code to Print Excel Sheets ,it's work Well but it print the all excel sheets from Open Excel workbooks, I need to Print Particular Sheets Only How can i do that Please help me..

I hope you.



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    John Bhatt
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India