如何解决CSOM不使用Windows凭据,并给出“远程服务器返回错误:403禁止”错误
我有一个使用.NET Framework的控制台应用程序,该应用程序使用CSOM上传文件。当我运行应用程序时,出现以下错误:
但是,当我通过Windows凭据时,它可以正常工作。由于安全目的,我不想在代码中对我的凭证进行硬编码。除了在代码中传递凭据以外,还有其他解决方法吗?
我的代码如下:
using System;
using System.IO;
using System.Linq;
using System.Security;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
ClientContext clientContext = new ClientContext("https://companyname.sharepoint.com");
//securestring passWord = new securestring();
//foreach (char c in "HelloWorld@1234".tochararray()) passWord.AppendChar(c);
//clientContext.Credentials = new SharePointOnlineCredentials("jay.desai@company.com",passWord);
clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
using(FileStream fileStream = new FileStream(@"C:\Users\jay.desai\Desktop\LSRsql01_ACXM_20201003.html",FileMode.Open))
ClientOM.File.SaveBinaryDirect(clientContext,"/sites/DataServices/Shared Documents/Data Dictionaries/LSRsql01_ACXM_20201003.html",fileStream,true);
}
}
}
解决方法
CSOM连接SharePoint Online需要SharePointOnlineCredentials。 测试演示:
static void Main(string[] args)
{
string userName = "amos@contoso.onmicrosoft.com";
Console.WriteLine("Enter your password.");
SecureString password = GetPassword();
using(var clientContext = new ClientContext("https://contoso.sharepoint.com"))
{
// SharePoint Online Credentials
clientContext.Credentials = new SharePointOnlineCredentials(userName,password);
// Get the SharePoint web
Web web = clientContext.Web;
// Load the Web properties
clientContext.Load(web);
// Execute the query to the server.
clientContext.ExecuteQuery();
// Web properties - Display the Title and URL for the web
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
Console.ReadLine();
}
}
private static SecureString GetPassword()
{
ConsoleKeyInfo info;
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
来源:https://www.c-sharpcorner.com/article/connect-to-sharepoint-2013-online-using-csom-with-console-ap/
已更新:
string siteUrl = "https://contoso.sharepoint.com/sites/demo";
using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl,"[Your Client ID]","[Your Client Secret]"))
{
cc.Load(cc.Web,p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。