ASP.NET Core 2.1 Identity: Role-based authorization -> Access Denied

后端 未结 2 1776
天涯浪人
天涯浪人 2020-12-10 07:27

I\'m using ASP.NET Core 2.1 with the new Identity framwork from .NET. The regular Authorization attribute works as long as no role specific role is requested.

相关标签:
2条回答
  • 2020-12-10 07:57

    It's a known issue in the version of 2.1 and has been fixed in 2.2 preview-1 .

    The reason is that the new method of AddDefaultIdentity<TUser>() , which is introduced in ASP.NET Core 2.1 , will not make Roles enabled by default .

    To walk around it , instead of using the new AddDefaultIdentity<TUser>() to configure Identity , simply use the old-style api :

    services.AddIdentity<AppUser, IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultUI()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();
    

    Also , if you have already signed someone in before , please do logout first and login again , it will work as expected now .


    [Edit] For ASP.NET Core 3.1, invoke .AddRoles<IdentityRole>():

    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<AppIdentityDbContext>();
    

    And then logout and login again.

    0 讨论(0)
  • 2020-12-10 08:09

    Hmmm. I have the following code in an Asp.Net 2.1 project that is working:

    services.AddDefaultIdentity<IdentityUser>()
             .AddRoles<IdentityRole>()
             //.AddDefaultUI(UIFramework.Bootstrap4)
             .AddDefaultTokenProviders()
             .AddEntityFrameworkStores<ApplicationDbContext>();
    
    0 讨论(0)
提交回复
热议问题