0

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.

mysqldatabase displaying registered test user

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(); Database record showing the test user is associated to the TestRole 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.
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
T3.0
  • 446
  • 1
  • 6
  • 21
  • did you try logout and then login again after registering? maybe the auth cookie is set before you added the role at registration time. – Joe Audette Feb 26 '19 at 21:07
  • @JoeAudette Thanks for the suggestion. Yes, I attempted logging out via the logout link and logging in again. – T3.0 Feb 26 '19 at 21:11
  • 1
    I resolved the issue by swapping the line in my startup.cs code `services.AddDefaultIdentity()` with `services.AddIdentity()` I don't want to post a code only answer and I don't understand why it resolved the issue so I will keep this as a comment for now. – T3.0 Feb 26 '19 at 23:12
  • 1
    @T3.0 If there are duplicate service registrations in .NET Core, it will resolve the last registered implementation of the type. Since `AddDefaultIdentity` just registers some default services and doesn't include role validation, I think it 'overrode' the `AddIdentity` registration, preventing it from recognizing the role. – Michael L. Feb 27 '19 at 01:19
  • 1
    @T3.0 See https://stackoverflow.com/questions/52531131/asp-net-core-2-1-identity-role-based-authorization-access-denied/52546946#52546946 – itminus Feb 27 '19 at 01:44

0 Answers0