gpt4 book ai didi

c# - 如何在 Azure 函数(客户端凭据流)中使用 Microsoft Graph SDK,而不使用 Microsoft.Graph.Auth

转载 作者:行者123 更新时间:2023-12-03 03:59:08 24 4
gpt4 key购买 nike

我一直在开发 Azure 函数。该功能是不需要用户交互的守护进程。因此,它使用应用程序权限来使用 Microsoft Graph。

这一想法是只有一个图形服务客户端实例,该实例将由该 Azure Functions 的所有实例使用。为此,我创建了一个单例类。

考虑到 Microsoft.Graph.Auth 处于预览阶段,并且永远不会退出预览,我选择使用 Microsoft.Identity 包。我将委托(delegate)传递给图形服务客户端,该委托(delegate)为客户端获取 token 。如果 token 过期,则会自动获取新 token 。 AcquireTokenForClient(scopes) 再次返回相同的 token ,但是,如果它即将过期,它将获取新的 token 。

  1. 问题是,考虑到可以运行多个 Azure Function 实例,这是否是处理 token 刷新的正确方法?
  2. 其次,使用 Microsoft.Identity 为图形服务客户端创建身份验证提供程序是否正确?或者有更好的办法吗?
  3. 最后,使用 Microsoft Graph SDK 是个好主意吗?因为,该文档使用的是 Microsoft.Graph.Auth,根据 Microsoft 的说法,它永远不会退出预览。没有太多关于如何以及做什么的文档。

我的代码:

    public class MSGraphAuth
{
private static MSGraphAuth _graphAuth;
private static GraphServiceClient _graphClient;
private static readonly object _lock = new object();

private MSGraphAuth() { }

public static MSGraphAuth GraphAuth
{
get
{
if (_graphAuth == null)
{
lock (_lock)
{
if (_graphAuth == null)
{
_graphAuth = new MSGraphAuth();
_graphAuth.InitializeGraphClient();
}
}
}

return _graphAuth;
}
}

public GraphServiceClient GraphClient
{
get
{
return _graphClient;
}
}

void InitializeGraphClient()
{
string authority = "{authority}";

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(AppSettings.MSGRAPHCLIENTID)
.WithAuthority(authority)
.WithClientSecret(AppSettings.MSGRAPHCLIENTSECRET)
.Build();

_graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{

var scopes = new string[] { "https://graph.microsoft.com/.default" };

var authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

}));
}

}
}

最佳答案

我使用类UsernamePasswordCredential创建与图形 API 交互的凭证。

var userNamePasswordCredential = new UsernamePasswordCredential(
userName, password, tenantId, clientId, options);

var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);

请记住:您可以在应用程序的生命周期内使用单个客户端实例。 Create a Microsoft Graph client

关于c# - 如何在 Azure 函数(客户端凭据流)中使用 Microsoft Graph SDK,而不使用 Microsoft.Graph.Auth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63182158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com