views:

1386

answers:

3

Hi I am using the SharePoint namespace for a webpart and I encounter some permission errors when I try to use the System account. Is there a way I can use a defined user instead of the system account?

Right now I have:

SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite site = new SPSite(_SPSite, sysToken))

I want to be able to use an account on the domain instead of the System account, thanks for any advice.

+1  A: 

You can use the SPUserCollection

SPContext.Current.Site.RootWeb.AllUsers

to get all of the users on the site, and get the SPUser from there. Once you have the SPUser you can get the UserToken.

Andy Mikula
+1  A: 

You may need to use RunWithElevatedPermissions to get access to the System account to work, as per the following blog post:

http://solutionizing.net/2009/01/06/elegant-spsite-elevation/

mundeep
The question was 'Is there a way I can use a defined user instead of the system account?'
Andy Mikula
The question also mentions "I encounter some permission errors when I try to use the System account", i was pointing out one possible reason that may have happened in the first place.
mundeep
A: 

What are you trying to do? If you don't use a token, the web will be opened with the same permissions as the current user

/* runs as user requesting the web part */
SPSite site = SPContext.Current.Web.site

or you can wrap it in the RunWithElevatedPrivileges delegate

/* runs with admin privileges */         
SPSecurity.RunWithElevatedPrivileges(
   delegate()
   {
      using (SPSite site = new SPSite(SPContext.Current.Web.Site.Url))
      {
        //do stuff
      }
   }
);
Jason