c# - Accessing Sharepoint online with MFA through C#
问题描述
I'd like to download a file from Sharepoint online using a non-interactive C# program. Recently MFA was enabled, and since then I'm unable to get the files with any user through my code, though I can still access it through the portal web access.
At first I have tried using the following, getting an The sign-in name or password does not match one in the Microsoft account system.
when executing the query (using either username@mydomain.com or username@mydomain.onmicrosoft.com)
var ctx = new ClientContext(Properties.Settings.Default.SharepointBaseUrl)
{
Credentials = credentials,
};
var web = ctx.Web;
ctx.Load(web);
try
{
ctx.ExecuteQuery();
}
catch (Exception ex)
{
return string.Empty;
}
var fileUrl = $"{web.ServerRelativeUrl}/{file.Location}";
var fi = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
Then I generated an AppId and AppSecret, and used the following code:
var authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
var ctx = authenticationManager.GetAppOnlyAuthenticatedContext(
"https://mydomain.sharepoint.com/sites/defaultcollection/MyDir",
appId,
appSecret);
But got a 401 unauthorized
when trying to access the file with SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
解决方案
像这样使用 File.OpenBinaryStream() 代替:
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core;
using System.IO;
string siteUrl = "https://tenant.sharepoint.com/";
using (var ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "yourappid", "yourappsecret"))
{
ctx.Load(ctx.Web, p => p.Title);
ctx.ExecuteQuery();
Console.WriteLine(ctx.Web.Title);
Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByUrl("https://tenant.sharepoint.com/Shared%20Documents/test.txt");
ctx.Load(file);
ctx.ExecuteQuery();
string filepath = @"C:\temp\" + file.Name;
Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();
ctx.ExecuteQuery();
using (var fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
{
mstream.Value.CopyTo(fileStream);
}
};
推荐阅读
- flutter - 在 Flutter 中集成 Stripe 支付
- javascript - 等待变量改变
- python-3.x - 高级搜索 API,使用 retweets_of 和 from 函数
- javascript - jsPDF 生成一个带有拉伸元素的 pdf
- visual-studio - 如何修复 CS0234 - 缺少装配参考
- amp-html - 是否可以选择使用 AMP 从电子邮件中上传照片/视频?
- jolt - 比较和组合相同数组的对象
- r - R数据框插入基于其他数据框的值
- excel - Excel VBA Range 'Delete' 方法随机失败
- c# - 当列表中不存在值时如何比较对象和List<>和object.value null