【问题标题】:Asp.net Web API .NET Core 3.1 and Azure AD - system.unauthorizedaccessexception: neither scope or roles claim was found in the bearer tokenAsp.net Web API .NET Core 3.1 和 Azure AD - system.unauthorizedaccessexception:在不记名令牌中找不到范围或角色声明
【发布时间】:2021-02-11 07:33:28
【问题描述】:

我正在尝试使用 Azure AD 保护我的 Web Api。此应用程序将由控制台应用程序访问,并且令牌将从客户端 ID/秘密生成。我遵循了来自https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-web-api 的快速入门。

获取客户端令牌并通过不记名身份验证标头发送后,出现错误

System.UnauthorizedAccessException:IDW10201:在不记名令牌中找不到范围或角色声明。

我正在使用此代码获取访问令牌:

       public static async Task<string> GetAccessToken(string aadInstance, string aadTenant, string aadClientId, string aadClientSecret, string apiResourceId)
    {
        string authority = aadInstance.TrimEnd('/') + "/" + aadTenant;
        var app = ConfidentialClientApplicationBuilder.Create(apiResourceId)
            .WithClientId(aadClientId)
            .WithClientSecret(aadClientSecret)
            .WithAuthority(authority)
            .Build();

        var tokenrequest = app.AcquireTokenForClient(new string[] { "api://resourceid/.default" });
        var tokenresult = await tokenrequest.ExecuteAsync();
        return tokenresult.AccessToken;

    }

我在 web api 中的启动代码如下所示:

       public void ConfigureServices(IServiceCollection services)
    {
        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration);

在启动后...

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseOpenApi();
        app.UseSwaggerUi3();
    }

【问题讨论】:

    标签: asp.net-core asp.net-web-api oauth-2.0 azure-active-directory


    【解决方案1】:

    事实证明,Azure AD 中的设置缺少需要添加到清单的角色以及客户端应用程序 api 的权限,如https://dotnetplaybook.com/secure-a-net-core-api-using-bearer-authentication/ 中的第 8 步所述

    很遗憾,MS 文档没有将这部分放在快速入门中。

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 2020-07-25
      • 2020-11-10
      • 1970-01-01
      • 2020-02-13
      • 2021-10-05
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多