尝试从Azure Fn项目连接到MS Graph API。

huangapple go评论73阅读模式
英文:

Trying to connect to MS Graph API from an Azure Fn Project

问题

我正在尝试在现有项目中创建一个新的 Azure 函数(az fn)... 我需要这个新函数在底层查询 Graph API。

以下代码不起作用,因为找不到 DelegateAuthenticationProvider 类的包/库:

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

var confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(ApplicationClientID)
            .WithTenantId(AzureTenantID)
            .WithClientSecret(ApplicationClientSecret)
            .Build();

// Build the Microsoft Graph client. As the authentication provider, set an async lambda
// which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
// and inserts this access token in the Authorization header of each API request. 
GraphServiceClient graphServiceClient =
    new GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider(async (requestMessage) => {

            // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
            var authResult = await confidentialClient
                .AcquireTokenForClient(scopes)
                .ExecuteAsync();

            // Add the access token in the Authorization header of the API request.
            requestMessage.Headers.Authorization = 
                new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        })
    );

以下是项目文件的内容:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <RootNamespace>widgets</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Identity" Version="1.9.0" />
    <PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
    <PackageReference Include="Microsoft.Azure.KeyVault" Version="3.0.5" />
    <PackageReference Include="Microsoft.Graph" Version="5.18.0" />
    <PackageReference Include="Microsoft.Graph.Core" Version="3.0.9" />
    <PackageReference Include="Microsoft.Identity.Client" Version="4.54.1" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
    <PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.6.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

我添加了以下依赖项以支持对 Graph 的调用:

<PackageReference Include="Microsoft.Graph" Version="5.18.0" />
<PackageReference Include="Microsoft.Graph.Core" Version="3.0.9" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.54.1" />

我理解 DelegateAuthenticationProvider 类是 Graph.Core 的一部分。

希望这只是一个非常简单的遗漏。任何提示将不胜感激。

英文:

I'm trying to create a new az fn in an existing project.... I need this new fn to query Graph Api under the hood.

The following code is not working because it can't find the package / library for DelegateAuthenticationProvider class:

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

        var confidentialClientApplication = ConfidentialClientApplicationBuilder
                    .Create(ApplicationClientID)
                    .WithTenantId(AzureTenantID)
                    .WithClientSecret(ApplicationClientSecret)
                    .Build();

        // Build the Microsoft Graph client. As the authentication provider, set an async lambda
        // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
        // and inserts this access token in the Authorization header of each API request. 
        GraphServiceClient graphServiceClient =
            new GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider(async (requestMessage) =&gt; {

                    // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                    var authResult = await confidentialClient
                        .AcquireTokenForClient(scopes)
                        .ExecuteAsync();

                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization = 
                        new AuthenticationHeaderValue(&quot;Bearer&quot;, authResult.AccessToken);
                })
            );

Here's the project file contents:

&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;AzureFunctionsVersion&gt;v4&lt;/AzureFunctionsVersion&gt;
    &lt;RootNamespace&gt;widgets&lt;/RootNamespace&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Azure.Identity&quot; Version=&quot;1.9.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Azure.Security.KeyVault.Secrets&quot; Version=&quot;4.5.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.KeyVault&quot; Version=&quot;3.0.5&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Graph&quot; Version=&quot;5.18.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Graph.Core&quot; Version=&quot;3.0.9&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Identity.Client&quot; Version=&quot;4.54.1&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Sdk.Functions&quot; Version=&quot;4.1.1&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Services.AppAuthentication&quot; Version=&quot;1.6.0&quot; /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;None Update=&quot;host.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
    &lt;/None&gt;
    &lt;None Update=&quot;local.settings.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
      &lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
    &lt;/None&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;

I added the following dependencies to support this call to graph:

&lt;PackageReference Include=&quot;Microsoft.Graph&quot; Version=&quot;5.18.0&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.Graph.Core&quot; Version=&quot;3.0.9&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.Identity.Client&quot; Version=&quot;4.54.1&quot; /&gt;

It's my understanding that DelegateAuthenticationProvider class is a part of Graph.Core.

Hopefully it's something super simple I've missed. Any tips would be appreciated.

答案1

得分: 1

你尝试的方法在 Microsoft.Graph.Core 包的第3个版本之后似乎已被弃用。这里 你可以找到迁移说明。

看起来你正尝试使用 ClientSecret 进行身份验证,我认为这是你在寻找的文档

文档中的代码:

// 客户端凭据流需要你请求 /.default 范围,并在 Azure 的应用注册中预先配置权限。
// 管理员必须事先同意这些权限。
var scopes = new[] { "https://graph.microsoft.com/.default" };

// 应用注册中的值
var clientId = "YOUR_CLIENT_ID";
var tenantId = "YOUR_TENANT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// 使用 Azure.Identity;
var options = new ClientSecretCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
英文:

The way you are trying to do it seems deprecated since Version 3 of the Microsoft.Graph.Core package. Here you find the migration description.

As it seems you are trying to authenticate via ClientSecret, I think this is the documentation you are looking for.

Code from the documentation:

// The client credentials flow requires that you request the
// /.default scope, and pre-configure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { &quot;https://graph.microsoft.com/.default&quot; };

// Values from app registration
var clientId = &quot;YOUR_CLIENT_ID&quot;;
var tenantId = &quot;YOUR_TENANT_ID&quot;;
var clientSecret = &quot;YOUR_CLIENT_SECRET&quot;;

// using Azure.Identity;
var options = new ClientSecretCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

huangapple
  • 本文由 发表于 2023年7月12日 23:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定