Impersonate as different user inside the webpart code

sharepointsharepoint-2007web-parts

I use the sharepoint lists as a database.
I want to somehow impersonate as different user inside the webpart code
and than as this user I will have both write and edit permission to the list.

My goal is to be able to have full premission only through the webpart code.

I am using MOSS 2007.

Best Answer

SPSecurity.RunWithElevatedPrivilieges() will execute your code as the system account, i.e. the account under which the application pool runs, which might or might not be what you want to do. For example, if you have a workflow attached to the list which is supposed to trigger when new items are added to the list, it will not fire if you insert a new list item under the credentials of the system account (this was a security fix introduced in SharePoint 2007 SP 1). In that case you will have to perform the insert operation under a different account that has the correct permissions on the list.

You can get the UserToken for any user using the following code:

        SPUserToken userToken = null;
        SPSecurity.RunWithElevatedPrivileges(() =>
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    userToken = web.AllUsers["domain\\username"].UserToken;
                }
            }
        });

Replace the "domain\username" with the correct windows account name. Then you can pass this user token to one of the overloads of the SPSite object constructor to execute the code under this user's credentials like so:

        using (SPSite site = new SPSite(SPContext.Current.Site.ID, userToken))
        {
            using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
            {
                // This code will execute under the credentials of the userToken user
            }
        }

Hope this helps.

Related Topic