CSOM 不使用 Windows 凭据并给出"The remote server returned an error: (403) Forbidden."错误



我有一个带有.NET Framework的控制台应用程序,它使用CSOM上传文件。当我运行应用程序时,我得到以下错误:

远程服务器返回错误:(403(Forbidden。

但是,当我通过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:Usersjay.desaiDesktopLSRSQL01_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);
};

相关内容

最新更新