【问题标题】:Need of scope parameter in Microsoft.Identity.Web downstream APIMicrosoft.Identity.Web 下游 API 中需要范围参数
【发布时间】:2022-01-16 11:05:16
【问题描述】:

我在我的 .netcore API 项目中使用 microsoft.Identity.Web 包,它调用 Graph API 来获取用户的目录对象。

在appsettings文件中,下游api设置如下,

"DownstreamApi": {
     "BaseUrl": "https://graph.microsoft.com/v1.0",
     "Scopes": "Directory.Read.All"
   },

相关权限(Directory.Read.All)在应用注册中设置。

但即使我将“Scope”参数留空,API 也会给我目录对象。

因此,如果设置是下面的格式,它仍然有效。那么这个scope参数有什么用呢?

"DownstreamApi": {
     "BaseUrl": "https://graph.microsoft.com/v1.0",
     "Scopes": ""
   },

【问题讨论】:

  • 如何生成访问令牌?显示你的代码 sn-p?

标签: .net-core azure-active-directory microsoft-graph-api


【解决方案1】:

范围声明可能没有反映在令牌中,因此您可能看不到与分配的范围有任何区别。

user_impersonation 是 Azure AD 中每个 Web 应用或 API 最初存在的默认委派权限/范围。

请务必在门户中添加所需的委派权限或应用程序权限。如果需要,请授予同意。

在您的情况下添加 directory.read.all 应用程序权限

例如:我添加了 user.read

应用设置:

"DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  },

在 startUp.cs 中

    Public void ConfigureServices(IServiceCollection services)
        {
            string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration)
       //  acquire a token to call a protected web API
               .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                .AddInMemoryTokenCaches();
               
          //

         //othercode
             ...
   }

在控制器中,我们需要指定范围并发送到请求标头以获取所需范围的访问令牌。

参考资料:

  1. call Microsoft Graph | Microsoft Docs (或)active-directory-aspnetcore-webapp-openidconnect-v2 (github.com)
  2. How can I create a new Azure App Registration without the user_impersonation OAuth2Permission? - Stack Overflow

如果 client_credentials 是授权类型,您可能需要在应用程序设置中使用 https://graph.microsoft.com/.default 作为范围,这将为您提供为您的应用程序定义的权限。

"DownstreamApi": {

    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "https://graph.microsoft.com/.default"
}

尝试在请求中使用 /token 端点,不常用

请看:
ASP.NET Core - Call Graph API Using Azure Ad Access Token - Stack Overflow-Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-11
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多