Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Applying Security to Server controls

0.00/5 (No votes)
11 Jan 2008 1  
You may have to give access or hide controls based on the user logged in. This article would help you write custom code to show/hide or enable/disable controls

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); 

}
  

/// <summary>

/// Page Level Access

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

/// </summary>

private void CheckPageAccess()

{

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

{

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

}

}


/// <summary>
/// DataGrid

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

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

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

/// <summary>

/// Configures access for controls

/// </summary>

public class AccessRight

{



#region AccessRight : Constructor

public AccessRight()

{ 

}

#endregion



#region Controls Access Rights

/// <summary>

/// Configures the access for controls

/// </summary>

/// <param name="htControl"></param>

/// <param name="iUserTypeCode"></param>

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

/// <summary>

/// Configures Grid Cell Contains multiple Controls

/// </summary>

/// <param name="dgGrid"></param>

/// <param name="iGridCellCode"></param>

/// <param name="collection"></param>

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

/// <summary>

/// Control AccessRight Pair Collection

/// </summary>

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

/// <summary>

/// Control AccessRight Pair

/// </summary>

public class ControlAccessPair

{

private Object custom_control;

private int code;

public ControlAccessPair()

{

}

/// <summary>

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

/// </summary>

/// <param name="control"></param>

/// <param name="accessCode"></param>

private ControlAccessPair(object control, int accessCode)

{

custom_control=control;

code=accessCode; 

}



/// <summary>

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

/// </summary>

/// <param name="customControl"></param>

/// <param name="Code"></param>

/// <returns></returns>

public static ControlAccessPair Add(object customControl, int Code)

{

ControlAccessPair controlAccessPair=new ControlAccessPair(customControl,Code);

return controlAccessPair;

}



/// <summary>

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

/// </summary>

/// <param name="customControl"></param>

/// <param name="Code"></param>

public void AddControl(object customControl, int Code)

{

custom_control=customControl;

code=Code;

}

/// <summary>

/// Returns the control

/// </summary>

public object GetControl

{

get

{

return custom_control;

}

}

/// <summary>

/// Returns the AccessCode

/// </summary>

public int GetCode

{ 

get

{

return code;

}

}

}

#endregion

#region Manage Cache Class

/// <summary>

/// Manage the AccessRights Cache

/// </summary>

public class ManageCache

{

private static ManageCache manageCache;

private static DataSet dsCahce;

/// <summary>

/// Static Constructor

/// </summary>

static ManageCache()

{

if (manageCache==null)

{

manageCache=new ManageCache();

dsCahce=new DataSet();

}

}

/// <summary>

/// Returns a boolean for the AccessCode

/// </summary>

/// <param name="AccessType"></param>

/// <param name="iAccessCode"></param>

/// <returns></returns>

public static bool GetAccessRight(string AccessType,int iAccessCode) 

{

return manageCache.AccessRight(AccessType, iAccessCode);

}

/// <summary>

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

/// </summary>

/// <param name="AccessType"></param>

/// <param name="iAccessCode"></param>

/// <returns></returns>

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here