Click here to Skip to main content
Click here to Skip to main content

Applying Security to Server controls

By , 11 Jan 2008
Rate this:
Please Sign up or sign in to vote.

Introduction

The access is Page Level, Control Level and the link level. We needed a generic way so that when implemented it is easy for the developers to replicate it for the whole project.

Technology Used: asp.net 1.1, C#, IIS6.0, Visual Studio 2003

Background

In one of the .Net Projects the customer required to control the access based on the role and the user. The access is Page Level, Control Level and the link level. We needed a generic way so that when implemented it is easy for the developers to replicate it for the whole project. I have modifed the code so that it is simple to understand and easily implemented. You can use the code in the following ways.

  1. Module Level Access Control: Wether a user logged in should be allowed to access the Module
  2. Page LeveL Access Control: To allow/deny the access for the web page if user permissions
  3. Feature Level Access Control: In a web page you may have many features, but you would like to give access permission to select users groups
  4. To hide/disable the server controls like button, link button, hyperlink, textbox, dropdownlist etc.
  5. To disable/hide the controls in the DataGrid, DataList, Repeater Controls
  6. The users could be in the group of administrators, operators Sales Reps, Sales Rep Admins etc.
  7. Apart from this if a user fall under a particular group, it will inherit the properties of that group. If you further fine tune the permissions for that group it could be possibe.

Using the code

// On Page Load call like below           
private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

ConfigureAccessRightControls();

}


private void ConfigureAccessRightControls()

{

AccessRight accRight=new AccessRight();

//Controls access

ControlAccessPairCollection controlAccessPairCollection=new ControlAccessPairCollection();

controlAccessPairCollection.Add(ControlAccessPair.Add(btn1, 1));

controlAccessPairCollection.Add(ControlAccessPair.Add(btn2, 2));

controlAccessPairCollection.Add(ControlAccessPair.Add(btn3, 3));



controlAccessPairCollection.Add(ControlAccessPair.Add(hlink1, 4));

controlAccessPairCollection.Add(ControlAccessPair.Add(hlink3, 6));

controlAccessPairCollection.Add(ControlAccessPair.Add(ddl1, 7));

controlAccessPairCollection.Add(ControlAccessPair.Add(ddl3, 9));



accRight.ConfigureAccess(ref controlAccessPairCollection); 

}
  

/// <span class="code-SummaryComment"><summary></span>

/// Page Level Access

/// If allowed then go Ahead, else deny access.

/// <span class="code-SummaryComment"></summary></span>

private void CheckPageAccess()

{

if (!AccessRight.GetAccessRight("Feature", 4))

{

Server.Transfer("../AccessRights/AccessDenied.aspx");

}

}


/// <span class="code-SummaryComment"><summary></span>
/// DataGrid

/// After datagrid is bound, then only we can give access rights to individual cells

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="sender"></param></span>

/// <span class="code-SummaryComment"><param name="e"></param></span>

private void dgCustomer_PreRender(object sender, EventArgs e)

{

//For a cell with multiple controls

AccessRight accRight=new AccessRight();

ControlAccessPairCollection controlAccessPairCollection=new ControlAccessPairCollection();

controlAccessPairCollection.Add(ControlAccessPair.Add("hypPreferred", 1));

//controlAccessPairCollection.Add(ControlAccessPair.Add("hypList", 2));

controlAccessPairCollection.Add(ControlAccessPair.Add("hypCopy", 0));

accRight.ConfigureAccess(ref dgCustomer, controlAccessPairCollection);

}


 
#region AccessRight class

/// <span class="code-SummaryComment"><summary></span>

/// Configures access for controls

/// <span class="code-SummaryComment"></summary></span>

public class AccessRight

{



#region AccessRight : Constructor

public AccessRight()

{ 

}

#endregion



#region Controls Access Rights

/// <span class="code-SummaryComment"><summary></span>

/// Configures the access for controls

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="htControl"></param></span>

/// <span class="code-SummaryComment"><param name="iUserTypeCode"></param></span>

public void ConfigureAccess(ref ControlAccessPairCollection collection) 

{



for(int iCount=0; iCount<collection.Count; iCount++)

{

ControlAccessPair controlAccessPair=new ControlAccessPair();

controlAccessPair=(ControlAccessPair)collection.Item(iCount);

object webControl=new object();

int iAccessCode;

webControl=controlAccessPair.GetControl;

iAccessCode=controlAccessPair.GetCode;

ConfigureControlAccess(ref webControl, "Feature", iAccessCode);

}

}

#endregion



#region Grid Access Rights

public void ConfigureAccess(ref DataGrid dgGrid, ControlAccessPairCollection collection) 

{

//for each row controls 



foreach (DataGridItem control in dgGrid.Items)

{

for(int iCount=0; iCount<collection.Count; iCount++)

{

ControlAccessPair controlAccessPair=new ControlAccessPair();

controlAccessPair=(ControlAccessPair)collection.Item(iCount);

object obj =(object)control.FindControl((string)controlAccessPair.GetControl);

ConfigureControlAccess(ref obj, "Feature", controlAccessPair.GetCode);

}

}

}

#endregion

#region DataList Access Rights

public void ConfigureAccess(ref DataList dList, ControlAccessPairCollection collection) 

{

foreach (DataListItem control in dList.Items)

{

for(int iCount=0; iCount<collection.Count; iCount++)

{

ControlAccessPair controlAccessPair=new ControlAccessPair();

controlAccessPair=(ControlAccessPair)collection.Item(iCount);

object obj =(object)control.FindControl((string)controlAccessPair.GetControl);

ConfigureControlAccess(ref obj, "Feature", controlAccessPair.GetCode);

}

}

}

#endregion



#region Repeater Access Rights

public void ConfigureAccess(ref Repeater repeater, ControlAccessPairCollection collection) 

{

foreach (RepeaterItem control in repeater.Items)

{

for(int iCount=0; iCount<collection.Count; iCount++)

{

ControlAccessPair controlAccessPair=new ControlAccessPair();

controlAccessPair=(ControlAccessPair)collection.Item(iCount);

object obj =(object)control.FindControl((string)controlAccessPair.GetControl);

ConfigureControlAccess(ref obj, "Feature", controlAccessPair.GetCode);

}

} 

}

#endregion



#region ConfigureAccess - Given the Cell Numbers

/// <span class="code-SummaryComment"><summary></span>

/// Configures Grid Cell Contains multiple Controls

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="dgGrid"></param></span>

/// <span class="code-SummaryComment"><param name="iGridCellCode"></param></span>

/// <span class="code-SummaryComment"><param name="collection"></param></span>

public void ConfigureAccess(ref DataGrid dgGrid,int iGridCellCode, ControlAccessPairCollection collection) 

{

//for each row controls 

for (int iGridCount=0;iGridCount<dgGrid.Items.Count;iGridCount++)

{

TableCell cell=new TableCell();

cell=dgGrid.Items[iGridCount].Cells[iGridCellCode];



for(int iCount=0; iCount<collection.Count; iCount++)

{

ControlAccessPair controlAccessPair=new ControlAccessPair();

controlAccessPair=(ControlAccessPair)collection.Item(iCount);

object webControl=new object();

int iAccessCode;

string CellControlID;

webControl=controlAccessPair.GetControl;

CellControlID=(string)webControl;

iAccessCode=controlAccessPair.GetCode;



if (cell.HasControls())

{

object obj=new object();

obj=cell.FindControl(CellControlID);

ConfigureControlAccess(ref obj,"Feature", iAccessCode);

}

}

}

}

#endregion



#region ConfigureControlAccess

private void ConfigureControlAccess(ref object webControl,string AccessType, int iAccessCode )

{

bool enabled=GetAccessRight(AccessType, iAccessCode);

if (enabled) return;

try

{

switch(webControl.GetType().ToString())

{

case "System.Web.UI.WebControls.TextBox": 

{

TextBox txtBox=new TextBox();

txtBox=(TextBox)webControl;

txtBox.Enabled=enabled; // based on the iAccessCode enable, disable, visible, invisible

break;

}

case "System.Web.UI.WebControls.DropDownList": 

{

DropDownList dropDownList=new DropDownList();

dropDownList=(DropDownList)webControl;

dropDownList.Enabled=enabled;

break;

}

case "System.Web.UI.WebControls.LinkButton": 

{

LinkButton linkButton=new LinkButton();

linkButton=(LinkButton)webControl;

linkButton.Enabled=enabled;

break;

}

case "System.Web.UI.WebControls.HyperLink": 

{

HyperLink hyperLink=new HyperLink();

hyperLink=(HyperLink)webControl;

hyperLink.Enabled=enabled;

break;

}

case "System.Web.UI.WebControls.CheckBox": //(typeof(CheckBox).ToString()):

{

CheckBox checkBox=new CheckBox();

checkBox=(CheckBox)webControl;

checkBox.Enabled=enabled;

break;

}



case "System.Web.UI.WebControls.ListBox": 

{

ListBox listBox=new ListBox();

listBox=(ListBox)webControl;

listBox.Enabled=enabled;

break;

}



case "System.Web.UI.WebControls.RadioButton": 

{

RadioButton radioButton=new RadioButton();

radioButton=(RadioButton)webControl;

radioButton.Enabled=enabled;

break;

}



case "System.Web.UI.WebControls.Button": 

{

Button button=new Button();

button=(Button)webControl;

button.Enabled=enabled;

break;

}



case "System.Web.UI.HtmlControls.HtmlAnchor":

{

HtmlAnchor htmlAnchor=new HtmlAnchor();

htmlAnchor=(HtmlAnchor)webControl;

htmlAnchor.Disabled=enabled;

htmlAnchor.Style.Add("cursor","default");

break;

}

case "System.Web.UI.HtmlControls.HtmlButton":

{

HtmlButton htmlButton=new HtmlButton();

htmlButton=(HtmlButton)webControl;

htmlButton.Disabled=!enabled;

break;

}

case "System.Web.UI.HtmlControls.HtmlInputButton":

{

HtmlInputButton htmlButton=new HtmlInputButton();

htmlButton=(HtmlInputButton)webControl;

htmlButton.Disabled=!enabled;

break;

}

case "System.Web.UI.WebControls.DataGrid": 

{

DataGrid dataGrid=new DataGrid();

dataGrid=(DataGrid)webControl;

dataGrid.Enabled=enabled;

break;

}

default:

{

break;

}

}

}

catch(System.NullReferenceException nullReferenceException)

{

throw new NullReferenceException("Not a valid cell type or control type.",nullReferenceException);

}

catch(Exception ex)

{

throw ex;

}

}

#endregion



#region GetAccessRight

public static bool GetAccessRight(string AccessType,int iAccessCode)

{

return ManageCache.GetAccessRight(AccessType, iAccessCode);

}

#endregion

}

 

#endregion


 

#region ControlAccessPairCollection Class

/// <span class="code-SummaryComment"><summary></span>

/// Control AccessRight Pair Collection

/// <span class="code-SummaryComment"></summary></span>

public class ControlAccessPairCollection:CollectionBase

{

public ControlAccessPairCollection()

{

}



public void Add(ControlAccessPair controlAccessPair)

{

List.Add(controlAccessPair);

}



public void Remove(int index)

{

// Check to see if there is a widget at the supplied index.

if (index > Count - 1 || index < 0)

// If no ControlAccessPair exists, a messagebox is shown and the operation 

// is cancelled.

{

//System.Windows.Forms.MessageBox.Show("Index not valid!");

}

else

{

List.RemoveAt(index); 

}

}

public ControlAccessPair Item(int Index)

{

// The appropriate item is retrieved from the List object and

// explicitly cast to the Widget type, then returned to the 

// caller.

return (ControlAccessPair) List[Index];

}

 

}

#endregion

#region ControlAccessPair Class

/// <span class="code-SummaryComment"><summary></span>

/// Control AccessRight Pair

/// <span class="code-SummaryComment"></summary></span>

public class ControlAccessPair

{

private Object custom_control;

private int code;

public ControlAccessPair()

{

}

/// <span class="code-SummaryComment"><summary></span>

/// Private constructor which initilizes the members of the class

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="control"></param></span>

/// <span class="code-SummaryComment"><param name="accessCode"></param></span>

private ControlAccessPair(object control, int accessCode)

{

custom_control=control;

code=accessCode; 

}



/// <span class="code-SummaryComment"><summary></span>

/// Creates an instance of ControlAccessPair Class and returns an object of it

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="customControl"></param></span>

/// <span class="code-SummaryComment"><param name="Code"></param></span>

/// <span class="code-SummaryComment"><returns></returns></span>

public static ControlAccessPair Add(object customControl, int Code)

{

ControlAccessPair controlAccessPair=new ControlAccessPair(customControl,Code);

return controlAccessPair;

}



/// <span class="code-SummaryComment"><summary></span>

/// Instance member to add the control and AccessCode to the object

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="customControl"></param></span>

/// <span class="code-SummaryComment"><param name="Code"></param></span>

public void AddControl(object customControl, int Code)

{

custom_control=customControl;

code=Code;

}

/// <span class="code-SummaryComment"><summary></span>

/// Returns the control

/// <span class="code-SummaryComment"></summary></span>

public object GetControl

{

get

{

return custom_control;

}

}

/// <span class="code-SummaryComment"><summary></span>

/// Returns the AccessCode

/// <span class="code-SummaryComment"></summary></span>

public int GetCode

{ 

get

{

return code;

}

}

}

#endregion

#region Manage Cache Class

/// <span class="code-SummaryComment"><summary></span>

/// Manage the AccessRights Cache

/// <span class="code-SummaryComment"></summary></span>

public class ManageCache

{

private static ManageCache manageCache;

private static DataSet dsCahce;

/// <span class="code-SummaryComment"><summary></span>

/// Static Constructor

/// <span class="code-SummaryComment"></summary></span>

static ManageCache()

{

if (manageCache==null)

{

manageCache=new ManageCache();

dsCahce=new DataSet();

}

}

/// <span class="code-SummaryComment"><summary></span>

/// Returns a boolean for the AccessCode

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="AccessType"></param></span>

/// <span class="code-SummaryComment"><param name="iAccessCode"></param></span>

/// <span class="code-SummaryComment"><returns></returns></span>

public static bool GetAccessRight(string AccessType,int iAccessCode) 

{

return manageCache.AccessRight(AccessType, iAccessCode);

}

/// <span class="code-SummaryComment"><summary></span>

/// Returns true if allowed, false for not allowed

/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param name="AccessType"></param></span>

/// <span class="code-SummaryComment"><param name="iAccessCode"></param></span>

/// <span class="code-SummaryComment"><returns></returns></span>

private bool AccessRight(string AccessType, int iAccessCode)

{

int typeCode = 1;// User.UserRoleCode; dynamically you can get the typecode

GetAccessRightsFromCache();

DataView dview =new DataView();

dview=dsCahce.Tables[0].DefaultView;

dview.RowFilter="ModulePageFeatureCode="+iAccessCode +" and UserTypeCode="+ typeCode;

if (dview.Count==0) //means there is no entry in the db so it is allowed

{

return true;

}

else

{

return false;

}

}

public void UpdateAccessRightsCache()

{

dsCahce.Tables.Clear();

GetAccessRightsFromCache();

}

private void GetAccessRightsFromCache()

{

//singleton Implementation

if (dsCahce.Tables.Count==0)

{

GetAccessRights(ref dsCahce);

}

//Cache Implementation

//Cache cache=HttpContext.Current.Cache;

//string cacheName="CACHE_ACCESSRIGHTS";



// if (cache[cacheName]==null)

// {

// GetAccessRights(ref ds);

// cache[cacheName]=ds;

// }

// else

// {

// ds=(DataSet)cache[cacheName];

// }

}

private void GetAccessRights(ref DataSet ds)

{



//AdminDA.AdminDA adminDA=new AdminDA.AdminDA();

//adminDA.GetAccessRights(ref ds);

//you can get access right detail for the user type or for the user from database or xml file

ds.ReadXml(HttpContext.Current.Server.MapPath("AccessRightsData.xml"));

}

}

#endregion 
 
 

Points of Interest

It was fun do do this code. Anyone can use this code in his project.

History

Feedback on my articel is most welcome. I will be keep this updated depending on the feedback.

You may also want to do

A module to control the features based on module, page or feature to be accessed by administrators. If it is a big application you may need to manage the features, modules, pages and allowable user groups to them.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Makesh Sanwal
Engineer SATYAM
United States United States
Enjoy developing/Architecting the software systems

Comments and Discussions

 
QuestionAn the article? Pinmembercambera8-Jan-08 20:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 12 Jan 2008
Article Copyright 2008 by Makesh Sanwal
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid