2023-01-15

Authorization Policy Attribute returns 403 and User.IsInRole returns false but claims are present WEB API Azure AD (Single Tenant)

Setup I have an ASP.NET Core MVC web app configured with Azure AD. I have an ASP.NET Core Web API configured Azure AD.

I obtain the token from Azure AD in the client web app and use it when requesting resources from the Web API, this works fine.

Issue The '[Authorize(Policy = 'policyName')]' attribute returns 403 and User.IsInRole() returns false in the WEB API controller, however when I remove the authorize policy attribute and check the user claims object, I can see the role present. Please check the image below

Claims Image enter image description here

RoleClaimType Image enter image description here

In my startup file I have configured token validation parameters of roleClaimType to be roles

`services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>{
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "roles";
});`
    public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();


        services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                .AddInMemoryTokenCaches();


        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

        services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
        {
            // Use the groups claim for populating roles
            options.TokenValidationParameters.RoleClaimType = "roles";
    
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy(Constants.AssignmentToAccountCreatorsRoleRequired, policy => policy.RequireRole(Constants.CAN_CREATE_ACCOUNT));
            
        });


        services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));



        //services.BuildServiceProvider().GetService<DbContext>().Database.Migrate();
        services.AddAutoMapper(typeof(Startup));

        services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

        //TODO: Replace CORS configuration
        services.AddCors(c => c.AddDefaultPolicy(policy => {
            policy.WithOrigins("https://localhost:44385", "https://someweb.net/")
           .AllowAnyHeader()
           .AllowAnyMethod();
        }));
        services.AddControllers();
        services.AddScoped<ConfigurationModel>();


        //services.AddScoped<GraphProfileClient>();
        //services.AddScoped<GraphEmailClient>();
        services.AddMemoryCache();


        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "NASACRM.API", Version = "v1" });

        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
        }
        else
        {
            app.UseHsts();

        }




        app.UseHttpsRedirection();

        app.UseRouting();
        app.UseCors();

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

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


No comments:

Post a Comment