[英]Accessing Sharepoint online with MFA through C#
我想使用非交互式 C# 程序在线从 Sharepoint 下载文件。 最近启用了 MFA,从那时起我无法通过我的代码获取任何用户的文件,尽管我仍然可以通过门户 web 访问来访问它。
起初我尝试使用以下方法,得到一个The sign-in name or password does not match one in the Microsoft account system.
执行查询时(使用 username@mydomain.com 或 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);
然后我生成了一个 AppId 和 AppSecret,并使用了以下代码:
var authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
var ctx = authenticationManager.GetAppOnlyAuthenticatedContext(
"https://mydomain.sharepoint.com/sites/defaultcollection/MyDir",
appId,
appSecret);
但是在尝试使用SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
访问文件时出现401 unauthorized
;
像这样使用 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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.