Azure Active Directory API 始终显示禁止消息

Azure Active Directory API always shown forbidden message

我是 Azure Active Directory 实施的初学者。我有一个带有 Azure Active Directory 保护的 WEB API (.net core)。我正在尝试通过 Postman 使用我的 WEB API,我知道它需要一个 Auth2 令牌才能使用 Web API。我已经按照 documentation link.

生成了 auth2 令牌

生成Auth2 token后,在header中添加auth2 token,如Authorization: Bearer e....但结果总是如下图所示。

我确定我会在 'API Permission' 部分提供所需的权限,并且 'Permission Type' 在 Azure 门户中是 'Delegated permissions'。

请看我的启动class:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(o =>
        {
            o.Filters.Add(new AuthorizeFilter("default"));
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddAuthorization(o =>
        {
            o.AddPolicy("default", policy =>
            {
                // Require the basic "Access app-name" claim by default
                policy.RequireClaim(DotNetCoreApiSample.Authorization.Constants.ScopeClaimType, "user_impersonation");
            });
        });

        services
            .AddAuthentication(o =>
            {
                o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.Authority = Configuration["Authentication:Authority"];
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // Both App ID URI and client id are valid audiences in the access token
                    ValidAudiences = new List<string>
                    {
                    Configuration["Authentication:AppIdUri"],
                    Configuration["Authentication:ClientId"]
                    }
                };
            });
        // Add claims transformation to split the scope claim value
        services.AddSingleton<IClaimsTransformation, AzureAdScopeClaimTransformation>();
    }

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

        // Very important that this is before MVC (or anything that will require authentication)
        app.UseAuthentication();

        app.UseMvc();
    }
}

根据我的测试,配置策略后,您可以使用范围 {your resource url}/user_impersonation 来请求访问令牌,然后您可以使用访问令牌调用您的应用程序。否则,您将收到 403 错误。请通过 link 检查您的访问令牌以确保您的范围

我的测试代码如下 1. Stratup.cs




 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var tenatId = Configuration["AzureAd:TenantId"];
              services
             .AddAuthentication(o =>
             {
                 o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
             })
             .AddJwtBearer(o =>
             {
                 o.Authority = "https://login.microsoftonline.com/<tenant id>/v2.0";
                 o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                 {




                     ValidIssuers = new[] {
                     "https://sts.windows.net/<tenant id>/",
                  "https://login.microsoftonline.com/<tenant id>/v2.0"



                     },
                    // Both App ID URI and client id are valid audiences in the access token
                    ValidAudiences = new List<string>
                     {
                    "<app id>",
                    "<app id url>"
                     }
                 };
             });
            services.AddAuthorization(o =>
            {
                o.AddPolicy("default", policy =>
                {
                  policy.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", "user_impersonation");
                });
            });
        }



        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseAuthentication();



            app.UseHttpsRedirection();
            app.UseMvc();
        }
  1. 测试

    一个。获取访问令牌

    b。调用 api