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...|
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With