如何在 ASP.NET MVC 应用程序中使用 AcquireTokenInteractive 设置 GraphServiceClient

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

我想在 ASP.NET MVC 应用程序中按照

this
示例使用 GraphServiceClient

由于我的问题得到了一些很大的帮助,我能够达到一个点,我需要添加

AcquireTokenInteractive
以修复以下错误(此处建议)

MsalUiRequiredException:没有帐户或登录提示传递到 AcquireTokenSilent 调用

DI 设置如下:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))                 
        .AddInMemoryTokenCaches();

出于测试目的,我将此代码放入

HomeController

private readonly GraphServiceClient _graphServiceClient;
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger, GraphServiceClient graphServiceClient, IConfiguration configuration)
{
    _logger = logger;

    _graphServiceClient = graphServiceClient;
    usrAsync();
}

async Task usrAsync()
{
    var user = await _graphServiceClient.Me.GetAsync();
    //The above line throws the MsalUiRequiredException 
}

如何设置

AcquireTokenInteractive

我使用以下软件包:

<PackageReference Include="Microsoft.Identity.Web" Version="2.15.2" />
<PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
<PackageReference Include="Microsoft.Identity.Web.GraphServiceClient" Version="2.15.2" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="2.15.2" />
c# asp.net-core microsoft-graph-api microsoft-graph-sdks
1个回答
0
投票

下面的代码是您所需要的吗?您分享的文档中没有

AcquireTokenInteractive
,但根据方法名称,它看起来像是用于获取访问令牌。由于您已经有了
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
,因此您可以将
ITokenAcquisition 
注入控制器,然后使用它来生成访问令牌。

public class HomeController : Controller
{
    private readonly ITokenAcquisition _tokenAcquisition;

    public HomeController(ITokenAcquisition tokenAcquisition)
    {
        _tokenAcquisition = tokenAcquisition;
    }

    public async Task<IActionResult> IndexAsync()
    {
        var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "api://xxx/Tiny.Read" });
    }
}

我下面的示例将为自定义 API 范围生成访问令牌,如果您想为 Graph API 生成令牌,您可以使用类似

new string[] { "User.Read", "Mail.Read" }
的范围。顺便说一句,由于您现在使用的是 Graph SDK,因此您不需要生成调用 Graph API 的访问令牌,只需使用 SDK 即可。

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