Asp.net Web API .NET Core 3.1和Azure AD-system.unauthorizedaccessexception:在承载令牌中未找到范围或角色声明

时间:2020-10-28 21:03:24

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

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

获取客户端令牌并通过Bearer Auth标头发送后,我收到了错误消息

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;

    }

我在网络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();
    }

enter image description here

1 个答案:

答案 0 :(得分:0)

事实证明,按照https://dotnetplaybook.com/secure-a-net-core-api-using-bearer-authentication/

不幸的是,MS文档没有将此部分放在快速入门中。

相关问题