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

标签 .net azure asp.net-web-api azure-active-directory azureportal

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

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

enter image description here

我确信我会在“API 权限”部分中授予所需的权限,并且 Azure 门户中的“权限类型”为“委派权限”。

请参阅我的启动类(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();
    }
}

最佳答案

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

enter image description here

我的测试代码如下 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();
        }
  • 测试

    a.获取访问 token

    enter image description here enter image description here

    b.调用api

    enter image description here

  • 关于.net - Azure Active Directory API 始终显示禁止消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60670082/

    相关文章:

    c# - .NET 中的 Finalize 和 Dispose 方法有什么意义? (回答前详见)

    c# - 在已连接的客户端上处理套接字异常10060

    node.js - 从本地上传 zip 在 azure blob 子容器中

    java - OpenSAML 如何检查 SAML 响应(签名/证书)是否确实来 self 的 IDP?

    c# - ASP.NET Web API 可以处理具有不同 Controller 的子资源吗

    c# - 为什么我的 ASP.NET Web API ActionFilterAttribute OnActionExecuting 没有触发?

    .net - 为什么 Microsoft .NET Framework Client Profile 是 256 MB?

    c# - DataSets to POCOs - 关于 DAL 架构的查询

    azure - 可靠的有状态服务与事件中心

    testing - 当 web api 仍在 iis 上运行时,如何在内存托管框架中使用组件测试 web api?