如何在不使用Microsoft.Graph.Auth的情况下在Azure Function(客户端凭据流)中使用Micr



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

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

考虑到Microsoft.Graph.Auth正在预览中,并且永远不会进行预览,我选择使用Microsoft.Identity包。我将委托传递给图形服务客户端,该客户端获取客户端的令牌。如果令牌过期,则会自动获取新的令牌AcquireTokenForClient(scopes(再次返回相同的令牌,但是,如果它即将过期,它将获得新的令牌。

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

我的代码:

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

I使用类UsernamePasswordCredential来创建一个凭证,以便与图形api交互。

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

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

最新更新