Impersonation in Sharepoint – MOSS/WSS

Here is the little code that you can use to impersonate any user in sharepoint. This will code will pretend that you are logged in as the user who is impersonated and will be allowed access to all the features and inherits all the rights for that person. This is mainly used to do something for which the impersonating person has rights and you other user do not have rights.

SPWeb web = SPContext.Current.Web.Site.OpenWeb();
SPUser user = web.AllUsers[username];
SPUserToken userToken = user.UserToken;
SPSite site = new SPSite(SPContext.Current.Web.Site.Url.ToString(), userToken);
web = site.OpenWeb();

Here username is the name username of the user who you want to impersonate as.

Hope this helps 🙂