如何为 SharePoint 在线 CSOM 验证 azure 函数

How to authenticate azure function for SharePoint online CSOM

我有一个 C# 代码,我想每天 运行 一次作为 Azure 函数。该函数应该连接到我的 SharePoint 站点并转换一些文档。 The code 我做了一些改动以满足我的需要。我纠结的部分是如何在接收相同上下文的同时进行身份验证并避免重构我的 function/app。如果我选择使用

AuthenticationManager am = new AuthenticationManager();
               
                using (var cc = am.GetSharePointOnlineAuthenticatedContextTenant(SiteUrl, userName, securePassword))

由于 2FA,身份验证存在问题。他们是互联网上推荐以下方法的一些帖子,但只有在我 运行 手动应用程序时它才有效。

using (var cc = authManager.GetWebLoginClientContext(SiteUrl))

据我了解,我可能需要证书。但是我不明白 SharePoint 站点如何知道此证书并获得 运行t 访问权限。还有很多例子都是关于使用 rest API 的,这很好,但在我的例子中,这意味着重构整个代码。那么有没有一种方法可以在不更改我当前使用的大部分 CSOM 代码并且不使用 REST API 和令牌的情况下验证我的功能?

From what I understood I probably need a certificate. However I can't understand how the SharePoint site will know about this certificate and grant the access.

这是使用名为 csomHelper.csx.

的 Azure 函数 class 脚本对 SharePoint Online CSOM 进行身份验证的示例代码
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.SharePoint.Client;
using System.Security.Cryptography.X509Certificates;

public static class csomHelper {
private static string ClientId = "(Application ID)";
private static string Cert = "(filename).pfx";
private static string CertPassword = "(password)";

private static string Authority = "[https://login.windows.net/](https://login.windows.net/)(tenantName).onmicrosoft.com/";
private static string Resource = "[https://](https:)(tenantName).sharepoint.com/";
public async static Task<ClientContext> GetClientContext(string siteUrl)
{

var authenticationContext = new AuthenticationContext(Authority, false);
var certPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "site\wwwroot\&lt;FunctionName&gt;\", Cert);
var cert = new X509Certificate2(System.IO.File.ReadAllBytes(certPath),

CertPassword,
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);

var authenticationResult = await authenticationContext.AcquireTokenAsync(Resource, new ClientAssertionCertificate(ClientId, cert));
var token = authenticationResult.AccessToken;
var ctx = new ClientContext(siteUrl);

ctx.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] ="Bearer "` `+ authenticationResult.AccessToken;
};
return ctx;
    }
}
  • 在上面的代码中,我们将App ID作为ClientId,证书文件名,密码和租户名称来获取wright登录名和资源URL。

  • var certPath行打开证书文件。

  • var authenticationResult 使用 cert 启动到 SharePoint 的身份验证流程。如果成功,应用程序将收到一个访问令牌,可用于访问 SharePoint。

  • 代码块从 var ctx 连接一个事件处理程序开始,只要 CSOM 执行请求,该事件处理程序就会 运行;它会将访问令牌插入到 HTTP header 中,以便请求由 SharePoint 授权。

欲了解更多信息,请访问此 article