tags:

views:

842

answers:

3

I have the following code snippet:

using (SPSite site = new SPSite(this.ListAddress))
        {
            using (SPWeb web = site.OpenWeb())
            {

            }

        }

How can I authenticate so that I can set a domain username + password in a configuration file.

+1  A: 

The code run above will autheticate under the current users identity, i.e. the identity of the user running the current thread.

You can run code under a different user using the NetworkCredntial class together with the WindowsIdentity class

See these two aticles:

http://msdn.microsoft.com/en-us/library/system.net.networkcredential%28VS.71%29.aspx

http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx

Lee Dale
This isn't the recommended approach for SharePoint. Much simpler to use Colin's code sample.
Alex Angas
+1  A: 

Not exactly clear what you want to do from the question. However if you are looking for impersonation, note that you can pass through an SPUserToken object in the SPSite constructor.

Any objects you then create from the impersonated SPSite object will behave as if they have been created by that user.

Alex Angas
+4  A: 

Make the user you want to run the code under known in SharePoint, then, using

SPSite.RootWeb.EnsureUser("username").UserToken you can get that user's SPUserToken use that to open the SPSite, like so

var token = SPSite.RootWeb.EnsureUser("usernameToImpersonate").UserToken;

using (SPSite site = new SPSite(token, this.ListAddress))
{
  using (SPWeb web = site.OpenWeb())
  {
    // code here will be executed as selected user
  }
}
Colin