Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0 unable to check if user is in role properly in Razor view or controller [authorize] annotation

I'm working on a legacy project with roles based authorization but I'm having some issues. User.IsInRole("admin") and [Authorize(Roles = "admin")] always failing Authorization. the User.IsInRole() always returns False. I'm pretty sure that user was properly added to the role. Role name 'admin' is already taken. User already in role 'admin'.

Maybe some service are influencing another.

Here is my startup.cs resumed code:

public void ConfigureServices(IServiceCollection services){

    services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connetctionString));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomUserClaimsPrincipalFactory>();
    services.AddMvc();
    services.AddDistributedMemoryCache();
    services.AddSession();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc(routes => {...});
}

What am I missing?

PS. Yes, I logged ou and login.

PS. Yes the user is in the role admin

PS. the "admin" are correct in lowercase

PS. ApplicationDbContext inherits IdentityDbContext

Ps2. Here is my Data

SELECT id,username FROM aspnetusers;

|id          | username        |
|c4f7bf16... | [email protected] |

SELECT Id,Name FROM aspnetroles;

|Id          | Name  |
|50e2a572... | admin |

SELECT * FROM aspnetuserroles;

|UserId      | RoleId     |
|c4f7bf16... | 50e2a572...|
like image 848
Daniel Santos Avatar asked Oct 11 '18 02:10

Daniel Santos


People also ask

How do I Authorize my razor page?

One way to control access in your Razor Pages app is to use authorization conventions at startup. These conventions allow you to authorize users and allow anonymous users to access individual pages or folders of pages. The conventions described in this topic automatically apply authorization filters to control access.

How can use Authorize attribute in core in asp net?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.


1 Answers

I have a feeling that this is because your Roles and your Claims are mixed up somewhere.

According to the docs the ClaimsPrincipal.IsInRole() method checks for Claims of type ClaimsIdentity.RoleClaimType.

It is possible to set a Claim of "admin" without it being of ClaimType ClaimsIdentity.RoleClaimType in which case it will fail authentication.

like image 178
ste-fu Avatar answered Oct 06 '22 01:10

ste-fu