从后台服务验证Sharepoint站点并上传文件

时间:2015-10-29 13:16:27

标签: c# sharepoint oauth office365 access-token

我尝试对Sharepoint进行身份验证,以便我可以将文件上传到特定的Sharepoint网站。

我试图使用X.509证书来检索访问令牌,但我一直在(401):未经授权。

以下是我尝试使用证书检索访问令牌的方式:

string authority = SettingsHelper.Authority;
string clientID = SettingsHelper.ClientId;
string serverName = SettingsHelper.SharepointServerName;
//Retreive the certificate path
string certFile = Server.MapPath(SettingsHelper.CertificatePath);
string certPassword = SettingsHelper.CertificatePassword;

AuthenticationResult authenticationResult = null;
AuthenticationContext authenticationContext = new AuthenticationContext(authority);

//Create the certificate file, using the path (certFile), password (certPassword) and the MachineKeySet
X509Certificate2 cert = new X509Certificate2(certFile, certPassword, X509KeyStorageFlags.MachineKeySet);

//Create the ClientAssertionCertificate using the clientID and the actual certificate
ClientAssertionCertificate cac = new ClientAssertionCertificate(clientID, cert);

//Retreive the access token using the serverName and client assertion
authenticationResult = authenticationContext.AcquireToken(serverName, cac);

以下是我尝试将特定文件上传到特定Sharepoint列表的方式:

WebRequest request = null;
HttpWebResponse response = null;
byte[] bytesToUpload = bytes;
var returnValue = "";

string requestUriString = string.Format("{0}/_api/web/GetFolderByServerRelativeUrl(@sru)/Files/Add(url=@fn,overwrite=true)?@sru='{1}'&@fn='{2}'", url, HttpUtility.UrlEncode(serverRelativeUrl), HttpUtility.UrlEncode(fileName));

request = (HttpWebRequest)HttpWebRequest.Create(requestUriString);

request.Method = "POST";
(request as HttpWebRequest).Accept = "*/*";
request.ContentType = "application/json;odata=verbose";
request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken));
request.ContentLength = bytesToUpload.Length;


// Write the local file to the remote system
using (Stream requestStream = request.GetRequestStream())
{
    BinaryWriter writer = new BinaryWriter(requestStream);
    writer.Write(bytesToUpload, 0, bytesToUpload.Length);
    writer.Close();
}
// Get a web response back
response = (HttpWebResponse)request.GetResponse();

using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
    returnValue = sr.ReadToEnd();
    sr.Close();
}

if (request.RequestUri.ToString().Contains("GetFolderByServerRelativeUrl") == true)
{
    returnValue = "";
}

有些变量来自参数:

 UploadEmail(System.IO.File.ReadAllBytes(emlFilePath), "https://(blablabla).sharepoint.com", "sites/(bla)/(bla)/Emails", email.Subject + ".msg");

我不确定错误是什么,我绝对不知道如何解决这个问题。

注意:请不要告诉我使用NetworkCredentials,我宁愿使用证书或其他内容,但不能使用NetworkCredentials

修改

管理调试代码并在WebRequest的响应头中找到它:

enter image description here

1 个答案:

答案 0 :(得分:1)

更好的方法是使用SharePoint客户端对象模型(如评论中建议的hbulens)。 这是在O365中将文件上传到库的代码(只需用您自己的详细信息替换字符串文字):

string username = "YOUR_USERNAME";
string password = "YOUR_PASSWORD";
string siteUrl = "https://XXX.sharepoint.com";

ClientContext context = new ClientContext(siteUrl);

SecureString pass = new SecureString();
foreach (char c in password.ToCharArray()) pass.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(username, pass);

Site site = context.Site;
context.Load(site);
context.ExecuteQuery();

Web web = site.OpenWeb("YOUR_SUBSITE"); 
context.Load(web);
context.ExecuteQuery();

List docLib = web.Lists.GetByTitle("YOUR_LIBRARY");
context.Load(docLib);

FileCreationInformation newFile = new FileCreationInformation();
string filePath = @"YOUR_LOCAL_FILE";

newFile.Content = System.IO.File.ReadAllBytes(filePath);
newFile.Url = System.IO.Path.GetFileName(filePath);

Microsoft.SharePoint.Client.File uploadFile = docLib.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();

您可以在控制台应用程序中运行它。您需要引用的两个dll是:

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll