这编译为startup.cs
:
string[] initialScopes = Configuration.GetValue<string>("GraphApi:Scopes")?.Split(' ');
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph();
但是,由于我只在处理 API 控制器,而不是 Web 应用程序,所以我想这样做:
string[] initialScopes = Configuration.GetValue<string>("GraphApi:Scopes")?.Split(' ');
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph();
但是,这不会编译。至少在Microsoft.Identity.Web
v1.0 中没有。Intellisense 告诉我string[] is not assignable to parameter type ConfidentialClientApplicationOptions
。
不同之处在于AddMicrosoftIdentityWebApiAuthentication
返回一个MicrosoftIdentityWebApiAuthenticationBuilder
,而前者返回一个 `MicrosoftIdentityAppCallsWebApiAuthenticationBuilder。
这里有解决方法吗?
我要完成的是确保在请求 Graph 访问令牌时正确设置范围。目前,情况似乎并非如此,因为我在尝试调用 Graph 时收到这样的错误 - 例如await graphServiceClient.Applications.Request().GetAsync();
。
---> Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException: IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.
---> MSAL.NetCore.4.18.0.0.MsalUiRequiredException:
ErrorCode: user_null
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was
换句话说,我需要的是一个如下所示的应用程序访问令牌:
[...more json]
{
"aud": "https://graph.microsoft.com",
"iss": "https://sts.windows.net/{tenant id}/",
"iat": 1602055659,
"nbf": 1602055659,
"exp": 1602059559,
"aio": "[...]",
"app_displayname": "My app",
"appid": "{App id guid}",
"appidacr": "1",
"idp": "https://sts.windows.net/{tenant id}/",
"idtyp": "app",
"oid": "{guid}",
"rh": "[...]",
"roles": [
"Application.ReadWrite.All",
"Directory.ReadWrite.All",
"Directory.Read.All",
"Application.Read.All"
],
"sub": "{guid}",
"tenant_region_scope": "EU",
"tid": "{tenant id}",
"uti": "[...]",
"ver": "1.0",
"xms_tcdt": 1597308440
}.[Signature]
我可以使用 Postman 手动生成上述内容,如果我使用它,它就可以工作。确认 Azure AD 中的应用程序配置正确。