I added Asp.Net Core 2.1 Identity to a project. I was successfully able to register a user and authenticate using the scaffoled views.
I have some code in the register.cs that automatically assigned the registered accounts to a role "TestRole" and verified in the database the role has been associated to the test account.
userManager.AddToRoleAsync(user, "TestRole").Wait();
When I add the
[Authorize]
attribute route attribute I get the expected behavior or the user being directed to the login screen if they aren't logged in. However when I use the [Authorize(Roles ="TestRole")]
attribute I'm denied access to the page although the authenticated account is associated to the "TestRole"
A similar SO QA (https://stackoverflow.com/a/46890346/1843966) had a popular answer of verifying the order of app.usemvc
in the startup but I have confirmed I'm doing this piece properly.
What would cause this to get denied when the account is associated to the specified role?
StartUp.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var context = services.AddDbContextPool<myAppContext>( // replace "YourDbContext" with the class name of your DbContext
options => options.UseMySQL("server=x.x.x.x;port=x;user=xyz;database=xyz;password=xyz"));
services.AddDefaultIdentity<myAppUser>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<myAppContext>();
services.AddAuthentication();
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider service)
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
dotnet console log:
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ForbidResult[1]
Executing ForbidResult with authentication schemes ().
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[13]
AuthenticationScheme: Identity.Application was forbidden.