在 ASP.NET Core Web 应用程序中获取TokenForUser

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

我在net6.0中有一个AspNetCore应用程序。 系统会要求用户登录 Azure Ad (Entra)。

完成此操作后,Web 应用程序需要调用 API。它到达的端点有范围要求。这是 Web 应用程序注册在 Azure 中拥有权限的范围。

如何获取包含该范围的令牌,以便我可以使用它在 API 中进行授权?我看过

_tokenAcquisition.AcquireTokenForUser
,但即使我在 pla 中拥有所有 AzureAd 配置(包括客户端密钥),它也会显示
no account or login hint was passed to AcquireTokenSilent

阅读文档让我感到困惑,并且很难找到我所追求的具体示例。 我在代码中尝试了不同的解决方案,但似乎都不起作用。

感谢任何帮助,如果需要更多信息,请告诉我,谢谢!

asp.net-core authentication .net-6.0 azure-ad-msal msal
1个回答
0
投票

根据错误提示,只能说您没有登录成功,导致

_tokenAcquisition
无法使用。由于您没有分享您如何编写代码,请允许我分享我的步骤。

首先,我创建了一个新的.net 8 mvc应用程序,在创建应用程序时,我选择“Microsoft Identity Platform”作为身份验证类型。然后我需要修改appsettings.json、Program.cs和HomeController。

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "ClientId": "aad_client_id",
  "ClientSecret": "client_secret",
  "Domain": "tenant_id",
  "TenantId": "tenant_id",
  "CallbackPath": "/signin-oidc"
},

在Program.cs中,添加toke获取服务,以及发送http请求的http服务。

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

builder.Services.AddHttpClient();

然后注入相关服务生成access token并发送http请求。

[Authorize]
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly ITokenAcquisition _tokenAcquisition;
    private readonly IHttpClientFactory _httpClientFactory;

    public HomeController(ITokenAcquisition tokenAcquisition, ILogger<HomeController> logger, IHttpClientFactory httpClientFactory)
    {
        _tokenAcquisition = tokenAcquisition;
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

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

        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7076/home/getData")
        {
            Headers =
            {
                { HeaderNames.Authorization, "Bearer "+ accessToken}
            }
        };

        var httpClient = _httpClientFactory.CreateClient();
        var response = await httpClient.SendAsync(httpRequestMessage);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            var result = await response.Content.ReadAsStringAsync();
        }
        return View();
    }

    [AllowAnonymous]
    public string getData() {
        return "success";
    }
}

就像您所看到的,在我登录应用程序并点击操作方法后,我可以成功生成访问令牌,其中包含我在方法中设置的正确范围。

我使用的Nuget包是由VS 2022模板生成的:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.0" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.Identity.Web" Version="2.15.2" />
  <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.15.2" />
  <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
</ItemGroup>
© www.soinside.com 2019 - 2024. All rights reserved.