The Wayback Machine - https://web.archive.org/web/20080430131810/http://www.codeguru.com:80/cpp/cpp/cpp_managed/general/article.php/c9093/

CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

jobs.internet.com

internet.commerce
Partners & Affiliates
Laptop Batteries
Internet Security
Dental Insurance
Build a Server Rack
Home Improvement
Promote Your Website
Promos and Premiums
Baby Photo Contest
Rackmount LCD Monitor
Career Education
Corporate Awards
Compare Prices
Remote Online Backup
Hurricane Shutters


RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> C++ >> Managed C++ >> General

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Managed C++: Determining User Security Roles
Rating:

Tom Archer - MSFT (view profile)
January 24, 2005

Go to page: 1  2  Next

In my previous article, "Managed C++: Retrieving User's Windows Security Information," I mentioned that there are times when an application can benefit from knowing specific Windows security information about a user. For example, in a recent spyware detection/removal system that I wrote, the code needed to delete certain files and, if those files were in use, mark them for deletion via the Registry. This latter part involved changing certain Registry keys that required that the user be defined in the Administrator group.


(continued)

Click Here

  Heroes Happen Here
New products, new technologies: Microsoft SQL Server 2008, Microsoft Visual Studio 2008, and Windows Server 2008 create new opportunities to use your existing skills and to grow your business. »


  Tips for Growing Your Microsoft Practice
You can grow your practice by increasing business with existing clients or adding more customers, expanding your practice areas or expanding your business into hosted or managed services. Discover which approach to growing your business makes the most sense for you and your customers. »


  Drive Your Business with Microsoft
Explore the business opportunities available through the Microsoft Partner Program, which is designed to help you generate leads, drive customer demand and sales, increase your profitability, and assess your business performance. »
  Partner-to-Partner Networking: A New Paradigm in Relationship Building
Heres a great way to build your business: Team up with partners whose solutions and services work as an extension of your own offerings. View this Webcast to learn how building networks with other partners can help your business grow. »
  IT Provider Grows Profits 85% in One Year with Microsoft Technologies
Knight Enterprises Inc., a longtime Novell partner, chose to add Microsoft technologies to its offerings after attending a Microsoft partner event. The company's major accounts soon followed suit, opting for Microsoft solutions over those of the competition. Download this case study to discover how Knight now expects its revenue to double in two years time. »

This article illustrates how to use the WindowsIdentity and WindowsPrincipal classes to test for a user's inclusion in a specified security group and how to use the PrincipalPermission class to perform a security check against the active principal.

Determining Role

The .NET security classes enable you to determine both authentication information regarding a user and specific role information (see Figure 1).

Figure 1. User Information Regarding Authentication and Specific Roles

As Figure 1 shows, I am an Administrator on the HOMEOFFICE domain. I determined this programmatically via the WindowsIdentity and WindowsPrincipal classes by taking the following steps:

  1. Include the necessary namespace:
    using namespace System::Security::Principal;
  2. Obtain the WindowsIdentity object associated with the current user:
    WindowsIdentity* identity = WindowsIdentity::GetCurrent();
  3. Create a WindowsPrincipal object based on the WindowsIdentity object. The WindowsPrincipal object contains information regarding the current user's group membership(s):
    WindowsPrincipal* principal = new WindowsPrincipal(identity);
  4. Call the WindowsPrincipal::IsInRole method, passing it either a string representing the role you are verifying or any of the members of the WindowsBuiltInRole enumeration type:
    bool isAdmin = principal->IsInRole(WindowsBuiltInRole::Administrator);

Using the PrincipalPermissions Object

Another way to check for the inclusion of a user in a security group is by using the PrincipalPermission class, which allows you to perform a security check against the active principal:

  1. Include the necessary namespaces
    using namespace System::Security::Permissions;
    using namespace System::Threading;
    
  2. Call the current domain's SetPrincipal method, passing to it the desired principal policy. Calling this method dictates how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal. In most cases, you'll pass the PrincipalPolicy::WindowsPrincipal enumeration member value so that operating system groups are mapped to security roles. Do this in situations where the code is making role-based security demands:
    AppDomain* dom = AppDomain::CurrentDomain;
    dom->SetPrincipalPolicy(PrincipalPolicy::WindowsPrincipal);
    
  3. Obtain the user's name via the current WindowsIdentity object:
    WindowsIdentity* identity = WindowsIdentity::GetCurrent();
  4. Instantiate a PrincipalPermissions object. When constructing this type, you must pass both the name of the user (the reason for the previous step) and the security group name. (Note that you cannot pass a WindowsBuiltInRole enumeration value, such as WindowsBuiltInRole::Administrator, here.)
    PrincipalPermission* permissions
      = new PrincipalPermission(identity->Name, "Administrators");
    
  5. In a try block, call the PrincipalPermission::Demand method before attempting to call code that is specific to a given user group's permissions. If the user does not belong in the group specified in the constructor of the PrincipalPermission object, a Security::SecurityException will be thrown. Therefore, placing a call to the Demand method at the top of a try block that then continues to security-specific code enables you to gracefully handle scenarios in which the user doesn't have the necessary security privileges to run the intended code:
    try
    {
      permissions->Demand();
    
      //... run code that requires the checked-for rights
    }
    catch(Security::SecurityException* ex)
    {
      // ex->Message will contain the exact error message
    }
    

About the Author
I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Go to page: 1  2  Next

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

Whitepaper: Embeddable Content Platform for OEM's
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.
Whitepaper: Elementool Bug Tracking--Keep Software Fixes On Course.
Intel Go Parallel Portal: Translating Multicore Power into Application Performance


RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
No Comments Posted.
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Solutions
Whitepapers and eBooks
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Avaya Article: How to Begin Developing with Avaya's Event Processing Language
HP eBook: Storage Networking , Part 1
ServerWatch.com Article: Tip of the Trade--IP Address Management
ITChannelPlanet.com Article: Enterprise Fixed-Mobile Convergence Can Be Lucrative
Hoover's Whitepaper Series: A Guide to Marketing in the Age of Social Media
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
Internet.com eBook: All About Botnets
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: Page Cost Calculator
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Partner Program Video: The Secrets to Partner Success
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
How-to-Article: How to Market Your Technology Solutions
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES