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

标签 c# sharepoint oauth office365 access-token

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

我正在尝试使用 X.509 证书检索访问 token ,但我一直收到 (401):未经授权。

这是我尝试使用证书检索访问 token 的方法:

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 的响应 header 中找到它:

enter image description here

最佳答案

更好的方法是使用 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

关于c# - 从后台服务验证 Sharepoint 站点并上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415317/

相关文章:

javascript - SharePoint `sender` 和 `args` 是什么?

c# - 使用zxing检测二维码

C# SqlConnection 停止于方法 : Open()

visual-studio-2010 - 团队系统 - 为现有团队项目创建 Sharepoint 项目门户

sharepoint - SPSecurityTrimmedControl 修剪内容时如何显示其他内容

c# - Facebook C# SDK 作为页面发布到页面

java - 使用 Java 和 Scribe 的 Vimeo 搜索 API

c# - 同一应用程序中 MVC 的 Cookie 身份验证和 WebAPI 的 OAuth

c# - 一次单击 2 个按钮

javascript - DIVstyle=none,但div仍然显示(用于弹出处理图形)