Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Dundas Dashboard
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Test for User Group Membership in ASP.NET C#

Test for User Group Membership in ASP.NET C#

This article describes a simple approach to determining whether or not a logged in user is a member of a group within the context of an asp.net web based application.

Author Rank:
Technologies: .NET 2.0, ASP.NET 2.0, Security,Visual C# .NET
Total downloads : 311
Total page views :  16829
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
NtGroups.zip
 
Become a Sponsor




Introduction

This article describes a simple approach to determining whether or not a logged in user is a member of a group within the context of an asp.net web based application. The approach shown is based on the use of Windows based authentication in conjunction with a web site configured to deny anonymous authentication and to require Windows based authentication.

The example shown would be useful on a company intranet site in which it was, for example, necessary to restrict access to certain parts of the available functionality based upon the member's role. For example, you might be working with an application that has administrative and general users; the administrative users might have additional application rights such as the ability to delete records. If one were to check for group membership in the administrator's group, the application can show or hide such functionality by getting the currently logged in user and checking whether or not that user is a group member.

There are other ways to accomplish the same sort of thing and to accomplish control level locking and the other approaches can be a bit more surgical; however, this is approach is quite easy and may be used to good effect.



Figure 1: Example Web Site showing results of a Group Membership Test

Getting Started:

In order to get started, unzip the included project and save it. Open IIS and create a virtual directory for the project and then, once it exists, right click on the web site and select "Properties". When the properties dialog box open, select the Directory Security tab and then click on the button called, "Edit"(Figure 2); this will open the "Authentication Methods"dialog box (Figure 3).



Figure 2: Edit the Anonymous Access and Authentication Settings



Figure 3: Authentication Methods

From the "Authentication Methods"dialog box, remove the check mark from "Anonymous Access"to disable the feature and check "Integrated Windows Authentication". This will force the site to require Windows Authentication which in most instances is transparent but running the application from a test instance on your local server will likely result in the display of a login dialog.

Once the settings are made, you can OK the dialog and close up the IIS control panel.



Figure 4: Solution Explorer

The solution contains a single web application project called "Default". In this case, all of the code necessary to run the demo is contained in the Default page's code behind file.

Code: Default Page

The default page contains a simple table used to display the results of a couple of quick tests; during operation, it will look like the screen shot shown in Figure 1. The markup for the page is little more than a simple table along with a bullet list and some labels used to display the user information.
The class begins with the default imports (all of the imports are set by default):

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

Following the imports, the class declaration is shown:

public partial class _Default : System.Web.UI.Page
{

Following the class declaration, the page load event handler is provided. The section is annotated to describe the action within Page Load:

protected void Page_Load(object sender, EventArgs e)
    {
        // collect the user domain and identity
        string[] arr =
            System.Web.HttpContext.Current.Request.
            LogonUserIdentity.Name.Split('\\');
 
        // update the display to show
        // the captured domain and user
        if (arr.Length > 0)
        {
            lblDomain.Text = arr[0].ToString();
            lblUser.Text = arr[1].ToString();
        } 

        // clear the list of groups
        BulletedListOfGroups.Items.Clear(); 

        // set the member of group label to no
        // as a default
        lblMemberOfGroup.Text = "NO";

         // create an arraylist and populate
        // it with the list of groups that
       // the current user belongs to
        ArrayList al = new ArrayList();
        al = GetGroups();
 
        // check to see if the user belongs
        // to a specific group and create
        // a list of all of the user's groups
        foreach (string s in al)
        {
            // add this one to the list
            BulletedListOfGroups.Items.Add(s);
 
            // check to see if the user
            // belongs to a specific group

            if (s == "BXSWLT\\SomeCustomGroup")
            {
                // change the label to show
                // there was a match
                lblMemberOfGroup.Text = "YES";
            }
        }
    }

The only other code contained in the default page's code behind is used to capture a collection of groups of which the user is a member. The captured group list is used in a simple test to see if the user is a member of a particular group in the page load handler:

/// <summary>
///
Get a list of all of the groups the current
/// user is a member of to support test of
/// MyLifeSpaceAdmin membership
/// </summary>
///
<returns></returns>
public ArrayList GetGroups()
{
ArrayList groups = new ArrayList();
foreach (System.Security.Principal.IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
groups.Add(group.Translate(typeof
(System.Security.Principal.NTAccount)).ToString());
}
return groups;
}
}

Code: Web.Config

This web.config file is in the default configuration; you need only check to make sure of the type of authentication specified for the application:

                    <authentication mode="Windows"/>

Make sure that the authentication mode is set to Windows.

That sums up all the code necessary to make this simple check for group membership.

Summary

The article is pretty short and simple. The intent was only to show an easy approach to determining whether or not a user is a member of a group in the context of a web application running with Windows NT Authentication. The approach may be useful as a means for controlling access to the entire application or parts of the application restricted from general use.

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
NtGroups.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
Exactly What I Have Been Looking For by Grammer On October 16, 2008
It works perfectly
Reply | Email | Delete | Modify | 
What about nested groups? by Courtney On November 17, 2008
You have demonstrated how to determine if a user belongs to a specific USER group but I need to verify that one of those groups I belong to belongs to another group. Any ideas? Thanks
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved