Chapter 26. How to Get a Token for a User

Getting a token (Item 16) for a user is tremendously easy if you happen to be running on a Windows Server 2003 machine in a native Windows Server 2003 domain. You can simply construct a new Windows Identity, passing in the user principal name (UPN) for the account, which for ACME\Alice is typically something like .[1] Here's an example:

using System;
using System.Security.Principal;

class IsUserAnAdmin {
  static void Main(string[] args) {
    if (1 != args.Length) {
      Console.WriteLine("Usage: IsUserAnAdmin userPrincipalName");
      return;
    }
    string upn = args[0];
    // here's the magic constructor
    WindowsIdentity id = new WindowsIdentity(upn);
    WindowsPrincipal p = new WindowsPrincipal(id);
 if (p.IsInRole(WindowsBuiltInRole.Administrator)) ...

Get The .NET Developer's Guide to Windows Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.