如何利用 GraphServiceClient 在基于应用程序的权限中进行依赖注入

问题描述 投票:0回答:1

我创建了一个接口和实现,每次使用下面的代码注入时,可以手动从 Azure 获取访问令牌:

using ARMS_API.CloudStorage;
using Azure.Identity;
using Box.V2.Config;
using Box.V2.JWTAuth;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.Graph;
using Microsoft.Graph.Drives.Item.Items.Item.CreateUploadSession;
using Microsoft.Graph.Models;

namespace ARMS_API.Azure
{
    public class AzureServices : IAzureServices
    {
        protected IConfiguration _configuration;        
        public AzureServices(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public GraphServiceClient GetGraphClient()
        {

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

            var chainedTokenCredential = GetChainedTokenCredentials();
            return new GraphServiceClient(chainedTokenCredential, scopes);

        }

        private ChainedTokenCredential GetChainedTokenCredentials()
        {
            var tenantId = _configuration["AzureAd:TenantId"]!;
            var clientId = _configuration["AzureAd:ClientId"]!;
            var clientSecret = _configuration["AzureAd:ClientSecret"]!;

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

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

            var chainedTokenCredential = new ChainedTokenCredential(devClientSecretCredential);

            return chainedTokenCredential;
        }
    }

}

但是,我希望我可以直接注入 GraphServiceClient ,类似于委托权限,您所做的就是在 program.cs 中设置您的服务,并在用户登录时自动检索令牌。我试图为应用程序实现此功能使用以下内容基于权限:

builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes: new string[] { "https://graph.microsoft.com/.default" })
.AddDistributedTokenCaches();

但是,没有任何东西可以让我实现类似于附加到 EnableTokenAcquisitionToCallDownstreamApi() 的委托权限的 .AddMicrosoftGraph() 。我在这里错过了什么吗?

asp.net-core microsoft-graph-api
1个回答
0
投票

尝试以下代码:

在Program.cs中

using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;

var builder = WebApplication.CreateBuilder(args);

TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
builder.Services.Configure<MicrosoftIdentityApplicationOptions>(
          option => tokenAcquirerFactory.Configuration.GetSection("AzureAd").Bind(option))
        .AddMicrosoftGraph()
        .AddInMemoryTokenCaches();

应用程序设置.json,

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "Tenant_Id",
  "ClientId": "Client_Id",
  "ClientCredentials": [
    {
      "SourceType": "ClientSecret",
      "ClientSecret": "Client_Secret_Value_here"
    }
  ]
},

这是我的控制器

private readonly GraphServiceClient _graphServiceClient;

public HomeController(GraphServiceClient graphServiceClient)
{
    _graphServiceClient = graphServiceClient;
}

public async Task<IActionResult> IndexAsync()
{
    var a = await _graphServiceClient.Users.GetAsync(r => r.Options.WithAppOnly());
    return View();
}

在我的示例中,它是 .net 8 MVC 并使用

<PackageReference Include="Microsoft.Identity.Web.GraphServiceClient" Version="2.18.1" />
,我参考了 这个示例

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.