0

我有一个 Blazor WASM 客户端应用程序正在尝试调用 aspnet web api。通过 Web API,我尝试使用具有委派权限的 Microsoft Graph SDK。

在服务器上,当我GraphServiceClient通过依赖注入检索实例时,尝试读取用户数据时出现以下错误。

var me = await graph.Me.Request().GetAsync();

StatusCode: 400 
    ResponseBody: {
        "error":"invalid_grant",
        "error_description":"AADSTS70000: The request was denied because one or more scopes requested are unauthorized or expired. The user must first sign in and grant the client application access to the requested scope.",
        "error_codes":[70000],
        "error_uri":"https://login.microsoftonline.com/error?code=70000",
        "suberror":"consent_required",
        (some data omitted)
     } 

但是,如果我使用 手动获取令牌ITokenAcquisition,则一切正常。

var token = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "User.Read" });

GraphServiceClient graph = new GraphServiceClient(new DelegateAuthenticationProvider(request =>
{
    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    return Task.CompletedTask;
}));
var me = await graph.Me.Request().GetAsync();


我的印象是注入的 GraphServiceClient 将使用 ITokenAcquisition 获取令牌并传递 Startup 中指定的范围。

我配置错了吗?似乎注入客户端中使用的令牌不包含正确的范围。

我已尝试完全退出我的 Microsoft 帐户,并删除浏览器缓存。我已同意所有必要的权限。

我的 api 服务器启动看起来像这样。

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddMicrosoftGraph(builder.Configuration.GetSection("GraphAPI"))
    .AddInMemoryTokenCaches();

服务器 appsettings.json

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "consumers",
    "ClientId": "{clientId}",
    "ClientSecret": "{clientSecret}",
    "Scopes": "AccessAsUser",
    "CallbackPath": "/signin-oidc"
  },
  "GraphAPI": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "User.Read"
  },

客户端启动

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.LoginMode = "redirect";
    options.ProviderOptions.DefaultAccessTokenScopes.Add("api://{clientId}/.default");
    options.ProviderOptions.DefaultAccessTokenScopes.Add("profile");
    options.ProviderOptions.DefaultAccessTokenScopes.Add("offline_access");

});

客户端 appsettings.json

  "AzureAd": {
    "Authority": "https://login.microsoftonline.com/consumers",
    "ClientId": "{clientId}",
    "ValidateAuthority": true
  }
4

1 回答 1

0

如果您尝试:

var me = await graph.Me.Request().WithScopes("https://graph.microsoft.com/.default").GetAsync();

使用 DI 注入的 GraphServiceClient 实例?

于 2021-11-26T18:13:50.200 回答