无法使用 EnableTokenAcquisitionToCallDownstreamApi 和 AddMicrosoftIdentityWebApiAuthentication 设置范围

Unable to set scopes with EnableTokenAcquisitionToCallDownstreamApi with AddMicrosoftIdentityWebApiAuthentication

这在 startup.cs 中编译:

string[] initialScopes = Configuration.GetValue<string>("GraphApi:Scopes")?.Split(' ');

services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
                .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph();

但是,由于我只在 API 控制器上工作,而不是网络应用程序,所以我想这样做:

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 returns一个MicrosoftIdentityWebApiAuthenticationBuilder而前者returns一个`MicrosoftIdentityAppCallsWebApiAuthenticationBuilder.

这里有解决方法吗?

我想要完成的是确保在请求图形访问令牌时正确设置范围。目前,情况似乎并非如此,因为我在尝试调用 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 中是正确的。

显然,目前尚不支持使用应用程序访问令牌。

IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user #667

使用

.AddMicrosoftGraph(Configuration.GetSection("GraphAPI"))

并确保你 appsettings.json 包含以下内容(使用你想要的范围 space 分隔):

  "GraphAPI": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read mail.read",
    "DefaultScope": "https://graph.microsoft.com/.default"
  }