Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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
add comment

1 Answer 1

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
add comment

Your Answer

 
discard

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.