0
votes

I have an ASP.NET Core 3.0 app. I am using Role-Based Authorization. My Startup.cs looks like this.

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddAuthentication().AddCookie();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Admin", authBuilder => { authBuilder.RequireRole("Admin"); });
    });
    services.AddIdentity<SiteUser, IdentityRole>(x =>
    {
        x.Lockout.AllowedForNewUsers = true;
        x.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2);
        x.Lockout.MaxFailedAccessAttempts = 3;
        x.Password.RequireNonAlphanumeric = true;
        x.Password.RequireUppercase = true;
    }).AddEntityFrameworkStores<SiteDbContext>();
    services.AddDbContext<SiteDbContext>(dbContextOptionBuilder =>
        dbContextOptionBuilder.UseLoggerFactory(ConsoleFactory)
            .UseSqlServer(Configuration.GetConnectionString(ConfigurationSettings.LocalDbKeyName)));
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error/500");
        app.UseStatusCodePagesWithReExecute("/Error/{0}");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllers();
    });

In my Controller class, I have appropriate Authorize attribute like so,

[Authorize(Roles = "Admin")]
public ActionResult Index()
{
    var users= getSomeUsers();
    return View(users);        
}

There are 2 roles in the AspNetRoles Table ie. Admin, and User. However, a user account without the admin role can access the Index action method. It is allowing any authenticated user to access the page and not limiting access to a user who possesses the right role that is the Admin role. What am I missing?

2
As explained in the answer of the duplicate question, the order is invalid, place app.UseRouting() before app.UseAuthentication().Ruard van Elburg
I beg to differ. It is not a possible duplication as the other thread uses JwtBearerDefaults and I use Identity. I suppose they are 2 different things.Ronnie Rahman
The reordering of the middleware did help. Thanks.Ronnie Rahman
That's why I marked this question as possible duplicate. The problem is the same, though the type of authentication is different, and so the answer is also valid here.Ruard van Elburg

2 Answers

0
votes

Though I initially accepted the answer of @Ruard van Elburg, however, the problem kept coming back mysteriously despite having the app.UseRouting(); before app.UseAuthorization(); app.UseAuthentication(); in the Configure method in my startup.cs file. So I started a new project and added the same files and to my surprise, it worked. After comparing every setting in the two projects, I found I had 'Enable SSL' turned off from the project Properties in the Debug tab.

So I Enabled SSL, and now it works just fine. If you are facing similar issues and rearranging the middleware didn't help, please check if you enabled SSL from the project properties page. Hope this helps someone.

0
votes

Check your user object if it has the admin role. You can remove this line from you code if you're using the roles property in authorize.

options.AddPolicy("Admin", authBuilder => { authBuilder.RequireRole("Admin"); });