1

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!!

7

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.

  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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