【发布时间】:2020-02-07 23:13:20
【问题描述】:
我有一种情况,我们使用 .net Core Web API 来管理一些“机器”。 公开的 API 之一是模拟此类机器的操作。 这些机器有不同的版本,每个不同的版本都有不同的内部行为,但界面相同。
然后,我们开发了一系列不同的 .net Core Web API 来模拟每个不同版本的机器。
因此我需要从 API 调用 API,这听起来很简单,因为我已经在使用 Microsoft Graph。
在 startup.cs 中,我有:
public void ConfigureServices(IServiceCollection services)
{
// To protect the API with Azure AD
services
.AddProtectedWebApi(Configuration);
// To have ITokenAcquisition when calling the specific simulation API
services
.AddMicrosoftIdentityPlatformAuthentication(Configuration)
.AddMsal(Configuration, new string[] { Configuration["SimulationAPIv411:Scope"] })
.AddInMemoryTokenCaches();
考虑到这一流程,我正在使用 Postman 对其进行测试:
- 我通过 Postman 获得了一个不记名令牌以访问通用 API
- Postman 在通用 API 中调用 SimulationDispatcherController
- SimulationDispatcherController 调用具体的模拟 API
- 结果流回 Postman
我正在经历的是:
-
如果我这样离开,在邮递员中我会得到一个登录页面
<!-- Copyright (C) Microsoft Corporation. All rights reserved. --> <!DOCTYPE html> <html dir="ltr" class="" lang="en"> <head> <title>Sign in to your account</title> [...] -
如果我删除
.AddMicrosoftIdentityPlatformAuthentication(Configuration)行,那么我可以到达 SimulationDispatcherController,但是当它尝试调用其他 API 时,我得到了错误:MSAL.NetCore.4.8.1.0.MsalUiRequiredException: ErrorCode: user_null Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call. [...]我尝试使用
ITokenAcquisition对象获取令牌,调用GetAccessTokenOnBehalfOfUserAsync(_Scopes);,其中范围是特定API 所需的范围。
您是否有任何建议或文档链接可以更好地解释如何在受 Azure AD 保护的 API 中配置 MSAL?
编辑: 正如答案中所建议的,唯一需要的更改是:
.AddMsal(Configuration, new string[] { Configuration["SimulationAPIv411:Scope"] })
到
.AddProtectedApiCallsWebApis(Configuration)
【问题讨论】:
标签: c# asp.net-core azure-active-directory msal