Azure Active Directory API always shown forbidden message

Viewed 281

I am a beginner in using Azure Active Directory Implementation. I have a WEB API (.net core) with Azure Active Directory protection. I am trying to consume my WEB API through Postman, I know it needs an Auth2 token for consume web API. I already generate the auth2 token as per this documentation link.

After generate the Auth2 token, add auth2 token in the header, like Authorization: Bearer e.... but the result always shows like below image.

enter image description here

I am sure I will give the required permission in 'API Permission' section and 'Permission Type' is 'Delegated permissions' in Azure Portal.

Please see my startup 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();
    }
}
1 Answers

According to my test, once you have configured the policy, you can just can use the scope {your resource url}/user_impersonation to require access token then you can call your application with the access token. Otherwise, you will get 403 error. Please check your access token via the link to ensure your scope

enter image description here

My test code is as below 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. Test

    a. get access token

    enter image description here enter image description here

    b. call the api

    enter image description here

Related