基于角色的授权在 ASP.NET Core 3.1 中不起作用

时间:2021-06-20 20:53:44

标签: asp.net-core authorization asp.net-identity role-based

[Authorize(Roles = "Admin")] 不适合我。

startup.cs (ConfigureServices) 我有:

    services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("defaultCon")));

    services.AddAuthentication().AddCookie();

    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddRoles<IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<AppDbContext>()
            .AddErrorDescriber<CustomIdentityErrorDescriber>()
            .AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();

Configure 方法中,我有:

    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Employee}/{action=list}/{id?}")
                .RequireAuthorization();
        });

我不知道我的错误是什么。

2 个答案:

答案 0 :(得分:0)

如果您使用基于 JWT 的授权,那么我们需要在 Claim Class 上添加角色,如下所示:

         var claims = new List<Claim> {
                new Claim("role", "Admin") // your person logged in role                                
         };

将角色添加到 Claim Class 后,authorize 标签应该会自动工作。

答案 1 :(得分:0)

看起来您的代码一切正常。顺便说一句,只需启用 SSL,我认为它应该可以正常工作。