How to pass credentials to httpwebrequest for accessing SharePoint Library

前端 未结 3 1270
庸人自扰
庸人自扰 2020-12-13 14:20

I\'m trying to read files from a SharePoint document library using HttpWebRequest. In order to do that I have to pass some credentials. I\'m using the below r

相关标签:
3条回答
  • 2020-12-13 14:33

    If you need to set the credentials on the fly, have a look at this source:

    http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709

    private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
        NetworkCredential cred;
        if (username.Contains(@"\")) {
            string domain = username.Substring(0, username.IndexOf(@"\"));
            username = username.Substring(username.IndexOf(@"\") + 1);
            cred = new System.Net.NetworkCredential(username, password, domain);
        } else {
            cred = new System.Net.NetworkCredential(username, password);
        }
        CredentialCache cache = new CredentialCache();
        if (authtype.Contains(":")) {
            authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
        }
        cache.Add(new Uri(siteurl), authtype, cred);
        return cache;
    }
    
    0 讨论(0)
  • 2020-12-13 14:53

    If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

    Your code looks fine if you need to run a request from server side code or under a different user.

    Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

    0 讨论(0)
  • 2020-12-13 14:54

    You could also use:

    request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
    
    0 讨论(0)
提交回复
热议问题