Claus on Code

A data dudes random musings about code, bugs, products, life etc.


Impersonating administrator

Developing to sharepoint 2003, you often need to access data, that only an administrator has access to. To do that in code, you need to impersonate an administrator. The classic solution looks like this. 

 

Add the following code to your project: 

private WindowsImpersonationContext ctx = null;
 public void UseAppPoolIdentity(){
  try{
   if (!WindowsIdentity.GetCurrent().IsSystem){
    ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
   }
  }

  catch{}
}
public void ReturnToImpersonatingCurrentUser(){
 try{
  if(ctx != null)
   ctx.Undo();
  }
  catch{}
 }
 

It is used from somewhere else in the code, like this:

UseAppPoolIdentity();
…Do something that only admins can do…
ReturnToImpersonatingCurrentUser(); 

But for some reason, this doesn’t always work, so you have to update the function: ReturnToImpersonatingCurrentUser(), so it looks like this: 

public void UseAppPoolIdentity(){
 try{
  if (!WindowsIdentity.GetCurrent().IsSystem){
   ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
   WindowsIdentity.Impersonate(WindowsIdentity.GetCurrent().Token);
  }
 }
 catch{}
}

Why this work, I don’t know. I guess it’s just one of sharepoints many special features 🙂



Leave a Reply

Your email address will not be published. Required fields are marked *