SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to impersonate another user by code.. I know in Sharepoint Enterprise there's a method which uses the UserProfileManager to impersonate...

I wrote down this "trace code" without know if it is right or wrong... Can anybody suggest me if i'm doing the impersonification in the right way?

private static void impersonateSpecificUser(string username, SPSite site, SPWeb currentWeb)
        SPUser user = currentWeb.EnsureUser(username);
        currentWeb.AllowUnsafeUpdates = true;
        HttpRequest request = new HttpRequest("", site.Url, "");
        HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
        HttpContext.Current.Items["HttpHandlerSPWeb"] = currentWeb;
        WindowsIdentity wi = WindowsIdentity.GetCurrent();
        typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(wi, user.LoginName);
        HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);

May it work on Sharepoint Foundation??

Thank you very much!!

share|improve this question
up vote 7 down vote accepted

You should use SPSite constructor override for this purpose.

The code will look something like this:

SPUser user = // grab the SPUser object somewhere
using (SPSite site = new SPSite("http://localhost", user.UserToken))
  using (SPWeb web = site.OpenWeb())
    // do whatever you need here

This will work in Foundation, too.

share|improve this answer
Simple and clean, I was just minutes away from submitting the same thing ;) – Falak Mahmood Feb 1 '12 at 13:50
2 questions:: 1. Is SPUser password required? For example can I impersonate as any user using this code without having the users password? 2. Can this method be used to access resources on filesystem like RWEP? – variable Aug 20 '14 at 8:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.