无法使用带有AddMicrosoftIdentityWebApiAuthentication

问题描述

文件startup.cs中进行编译:

string[] initialScopes = Con@R_502[email protected]<string>("GraphApi:Scopes")?.Split(' ');

services.AddMicrosoftIdentityWebAppAuthentication(Con@R_502_6408@uration)
                .EnabletokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph();

但是,由于我只使用API​​控制器,而不是Web应用程序,因此我想这样做:

string[] initialScopes = Con@R_502[email protected]<string>("GraphApi:Scopes")?.Split(' ');

services.AddMicrosoftIdentityWebApiAuthentication(Con@R_502_6408@uration)
                .EnabletokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph();

但是,这不能编译。至少不是Microsoft.Identity.Web v1.0。 Intellisense告诉我string[] is not assignable to parameter type ConfidentialClientApplicatio@R_404_6457@tions

不同之处在于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中应用程序的配置正确。

解决方法

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

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

,

使用

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

并确保您的 appsettings.json 包含以下内容(使用您想要用空格分隔的 Scope):

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