Programmatic impersonation in C#


I recently deployed a WPF app on a server that allowed the user to stop and start some application-related services. The purpose of the app was to allow users with administrative rights an easy way to manage the services that they needed to manage. Granted, they could manage the services through the services MMC, but the little WPF app was a requirement, and it’s our job as developers to make things easier for our clients – right?

All went well until a change of requirements meant that a user without administrative rights needed to use the program to stop and start the required services. When I tried to use the app, I got an exception – quite rightly, stopping and starting the services required admin rights. We needed the restricted user to be able to log on and use the app, but still needed to restrict their permissions.

So – step in programmatic impersonation in C# – a way to give restricted users the power that that’s required, all within the confines of your application.

The first thing to point out is that I got quite a bit of this code from a google search, but I had to do a bit of work to get things in a state that I found really useful.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Linq;
using System.Security.Principal;
using System.Text;
namespace ServiceControllerApp.Security
    public class Impersonator : IDisposable
        private WindowsImpersonationContext _impersonatedUser = null;
        private IntPtr _userHandle;
        public Impersonator()
            _userHandle = new IntPtr(0);
            string user = "servicecontroller";
            string userDomain = ConfigurationManager.AppSettings["MachineDomain"];
            string password = "yourpassword";
            bool returnValue = LogonUser(user, userDomain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _userHandle);
            if (!returnValue)
                throw new ApplicationException("Could not impersonate user");
            WindowsIdentity newId = new WindowsIdentity(_userHandle);
            _impersonatedUser = newId.Impersonate();
        #region IDisposable Members
        public void Dispose()
            if (_impersonatedUser != null)
        #region Interop imports/constants
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_LOGON_SERVICE = 3;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern bool LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

Impersonator is a simple class that uses interop to call Win32 LogonUser and CloseHandle functions. We have to use interop because .NET doesn’t provide the equivalent methods.

The code shown above has a user, domain and password actually in the code – for some situations this is a security risk, so the credentials should be obtained in another manner, but for my needs, it was satisfactory, and their direct inclusion simplifies this example.

The class has a WindowsImpersonationContext to manage the impersonation, and the constructor sets up the required logon rights using the LogonUser interop.

Crucially, the impersonation must end, with an equivalent Log Off – and the class implements IDisposable to call the required log off code. Using the class is easy.

using (Impersonator impersonator = new Impersonator())
    // code in here

The good thing is that because the class implements IDisposable, you don’t have to pepper your code with the log off code equivalent. I hope it’s of use to somebody wishing to implement impersonation.

Fieldrunners iPhone Game Review

Fieldrunners Review

I greeted the launch of the AppStore with great excitement and expectation, especially since a version of Monkey Ball was to be released that very same day. I was however disappointed with the iPhone incarnationl, and outlined my reasons in my review. Despite pretty graphics, over-sensitive controls made the gameplay non-existent. In addition, other games that grabbed my interest also disappointed with poor controls and use of the iPhone’s accelerometer.

Spore Origins was better than I thought, with finer control over movement, but I found the gameplay rather shallow. Disappointment once again.

A couple of weeks ago, I found a gem of a game, and refreshingly, it didn’t use the accelerometer, and the touch screen interface was implemented perfectly. Not only this, but it was fun to play, addictive, and graphically reminiscent of SNES games from an era of games that I loved. That game is Fieldrunners, currently standing at Number 12 in the top paid apps in the App Store. With an average score of 5 stars from 199 reviewers, it’s obviously got it’s followers, and I’m one of them.

Fieldrunners at number 12 in the paid apps chart.
Fieldrunners at number 12 in the paid apps chart.

Developed by Subatomic Studios, the game is a Tower Defence derivative where you have to construct a series of defence towers to protect yourself against wave after wave of air and land combatants.

Version 1.0 of the game was released on October 15, and was a cracking game in its own right, but lacked a sound and music, and had just the one map. A free upgrade, version 1.1, was launched yesterday and features excellent sound and music, and an additional map that extends the lifespan of the game. The game offers three levels of difficulty, and comprises of 100 waves of attack that must be resisted. For each enemy unit that makes it across the field, one of 20 lives is lost. The game ends when either all lives have been lost or 100 waves have passed. The new version also offers an ‘endless’ mode where the number of waves is endless and the game ends only when the player loses their 20 lives. 20 lives may sound a lot, but the waves are relentless and things can get quite hectic. The animation is fantastic and makes the game a pleasure to watch as much as actually play.

A good overview of the game in play is available over at YouTube:

The game is simple to learn, and the following help screens perfectly describe what the game is all about:

Building towers for defence
Building towers for defence

Upgrading defences
Upgrading defences

Building strategic routes
Building strategic routes

Tower types
Tower types

For anybody who hasn’t yet got the update, here is a screenshot of the new ‘Crossroads’ level:

New level Crossroads
New level 'Crossroads'

At only £2.99, the game is an absolute steal, and my faith in iPhone gaming has been restored!