通过c#使用MFA在线访问Sharepoint



我想使用非交互式c#程序从Sharepoint在线下载一个文件。最近启用了MFA,从那时起,我无法通过我的代码与任何用户获得文件,尽管我仍然可以通过门户网站访问它。

首先,我尝试使用以下方法,在执行查询(使用username@mydomain.com或username@mydomain.onmicrosoft.com)时获得The sign-in name or password does not match one in the Microsoft account system.

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);
}
};

最新更新