Tuesday, April 21, 2015

Impersonating user in Sharepoint Server Object Model

Hi Readers,

I came across a requirement to upload some files using a console application to sharepoint, but there was a workflow which needed to started when an item is added, so using System Account was not an option.

This is a way to impersonate the user and access the web.


//Connect to the site as System Account
using (SPSite site = new SPSite("Site URL"))
{
    using (SPWeb web = site.OpenWeb())
    {
        //Get the spuser object from the site
        SPUser userToImpersonate = web.EnsureUser(@"Domain\username");

        //Connect to the site again using the Token
        using (SPSite impSite = new SPSite("Site URL", userToImpersonate.UserToken))
        {
            using (SPWeb web2 = impSite.OpenWeb())
            {
                //Impersonated Block
            }
        }
    }
}



Happy Coding
Guruparan Giritharan

No comments:

Post a Comment