【问题标题】:AspNetCore MVC Claims - IsInRoleAsync verus ClaimsAspNetCore MVC 声明 - IsInRoleAsync 验证声明
【发布时间】:2019-06-09 20:36:00
【问题描述】:

在我的 aspnet 核心 MVC 应用程序中,如果我使用注入的 UserManager 检索用户,则以下返回 true

await _userManager.IsInRoleAsync( user, "Administrator" );

但是,每当我在这样的视图中检查 User (ClaimsPrincipal) 时,声明就会丢失(返回 false):

User.IsInRole( "Administrator" );

这对我来说似乎不一致。

我是否必须自己在某个地方手动设置角色声明?我想这将是免费的,并且自定义 UserClaimsPrincipalFactory 将用于特定于应用程序的声明,而不是角色(MVC 开箱即用)。

我错过了什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-core


    【解决方案1】:

    这是 2.1 版本中的一个已知问题,已在 2.2 preview-1 中修复。

    在asp.net core 2.1中,使用AddDefaultIdentity,注入变为

    services.AddDefaultIdentity<IdentityUser>()
                .AddRoles<IdentityRole>()
    

    ,默认情况下不会启用Roles,并且对于User.IsInRole,它总是返回false。

    绕过它,而不是使用新的AddDefaultIdentity&lt;TUser&gt;()来配置Identity,只需使用旧式api:

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

    另一种方法是您可以将 UserClaimsPrincipal 工厂替换为具有角色意识的工厂。在 ConfigureService 中添加以下代码并参考 UserRoles in DefaultIdentity

    services.AddScoped<IUserClaimsPrincipalFactory<IdentityUser>, UserClaimsPrincipalFactory<IdentityUser, IdentityRole>>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2015-04-15
      • 2012-07-03
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多