【问题标题】:How to use Roles in ASP.NET Core 2.1?如何在 ASP.NET Core 2.1 中使用角色?
【发布时间】:2018-05-19 14:20:44
【问题描述】:

我创建了一个测试项目,使用:

dotnet new razor --auth Individual --output Test

这将创建一个 Startup.cs,其中包含:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

我想播种一些用户和角色。用户和角色都将使用相同的存储 (SQLite)。我正在使用从 Program 调用的静态类进行播种。

我可以为用户播种,但不能为角色播种,因为上面似乎没有注入RoleManager。

在 ASP.NET Core 2.0 中使用以下内容:

services.AddIdentity<IdentityUser, IdentityRole>()

我猜AddDefaultIdentity 是 2.1 中的新功能,但问题是它没有注入 RoleMnager,那我该怎么办?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-identity asp.net-core-2.1


    【解决方案1】:

    微软似乎终于明白并不是每个应用程序都需要角色并将它们分开。

    注意AddDefaultIdentity 被声明为:

    public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services) where TUser : class;
    

    因此,您可以继续通过 IdentityBuilder 配置身份选项。你想做的是:

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

    幸运的是,他们还删除了 IUser 和 IRole 约束,因此现在您可以在完全独立的程序集中使用模型,而无需安装数百个 NuGet 包。

    【讨论】:

    • 太棒了!我可以确认这是我想要的。感谢您的快速回复。
    • 你就是传奇。我被困在这个问题上,并且一直在寻找很多天的解决方案。这个解决方案解决了我所有的问题。
    • 角色是否与身份相关联?如果我不使用身份并且我的 JWT 令牌在其中包含角色怎么办?那我可以使用 .AddRoles 吗?
    • @variable 那么这与身份完全无关 - 即您不能在此问答中使用 AddRoles 或其他任何内容。但是,如果正确配置了 ASP.NET Core,您可以让它自动使用 JWT 中的角色
    • 在这种情况下我可以使用AuthorizationHandlerContext.User.IsInRole吗?如果没有,我应该使用HttpContext.Current.User...吗?
    【解决方案2】:

    可能对其他人有帮助:如果您通过脚手架将 asp.net 身份添加到现有项目,则需要编辑 IdentityHostingStartup.cs 并更改那里的服务,而不是在您的启动类中:

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

    然后您可以在播种中使用角色管理器。

    【讨论】:

    【解决方案3】:

    除了已经提供的答案之外,尽管添加了.AddRoles&lt;Identity&gt;(),但在我的控制器上使用Authorize(Roles = "Administrator") 时仍然无法获得授权。出于某种原因,“角色声明似乎不会影响带有角色名称的 IsUserInRole 或 AuthorizeAttribute。”

    为了使用角色,我建议使用 ASP.NET 2.0 方式,如下所示:

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

    这样,您可以使用自己的角色,并为您搭建身份页面。

    参考aspnet github上的这个问题: Issue 1813

    【讨论】:

    • 我也偶然发现了这一点,但没有更新我上面的回复。我的 IdentityHostingStartup.cs 文件现在包含: services.AddIdentity() .AddDefaultUI() .AddRoles() .AddRoleManager>() .AddDefaultTokenProviders() .AddEntityFrameworkStores() ;
    【解决方案4】:

    从 .Net Core 2.1 开始,AddDefaultIdentity 与调用相同:

    • AddIdentity
    • AddDefaultUI
    • AddDefaultTokenProviders

    要添加角色功能,请转到ConfigureServices 下的Startup.cs,您可以像这样使用.AddRoles:

    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()            //<-- This line
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    这就是我们所需要的。注销并重新登录至关重要。

    为了记录(并且只是为了测试),我尝试了services.AddIdentity:

    IServiceCollection 不包含“AddIdentity”的定义...

    和services.AddIdentityCore(在调试和显示页面之前没有错误):

    InvalidOperationException:未指定 authenticationScheme,并且 没有找到 DefaultChallengeScheme。默认方案可以是 使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions)。

    你可以做更多的事情来让后两个工作,但我为AddDefaultIdentity 发布的代码是我需要的,以便让User.IsInRole 和其他角色功能在 .NET Core 2.1(和 3.1 )。

    【讨论】:

      【解决方案5】:

      不久前我也曾与这个问题作过斗争。我无法让角色发挥作用。

      在我的项目中,我使用了 ASP.NET Core 2.1(它可以在 2.2 中修复,请参阅链接)并且还搭建了一些页面。

      在网上长时间搜索后,我找到了这个解决方案(上面Issue 1813也提到过)

      我的解决方案是(如文章中所建议的)在 IUserClaimsPrincipalFactory 中添加以下行:

              services.AddScoped<IUserClaimsPrincipalFactory<IdentityUser>, 
                  UserClaimsPrincipalFactory<IdentityUser, IdentityRole>>();
      
              services.AddDefaultIdentity<IdentityUser>()
                  .AddRoles<IdentityRole>()
                  .AddRoleManager<RoleManager<IdentityRole>>()
                  .AddDefaultTokenProviders()
                  .AddEntityFrameworkStores<TranslatorDbContext>();
      

      【讨论】:

      • 谢谢你,这对我重新启用角色很有帮助
      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2020-10-15
      相关资源
      最近更新 更多