根据在其他地方读到的建议,角色是声明的子集,我正在寻找一种干净的方法来要求 ASP.NET Identity 中的 EF Core 实现不要在 VS 的 ASP.NET Identity Core 2.0 模板中创建与角色相关的表2017. 只需要索赔。
模板使用
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
IdentityDbContext 创建这些与 Roles 相关的表
https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity.EntityFrameworkCore/IdentityDbContext.cs
如何在不操作迁移文件的情况下摆脱它们?
这在 ASP.NET Identity 中一直是可能的,但随着时间的推移,它变得更加容易,因为约定已经从角色转向权利、操作、声明、谓词和其他更可重用和可维护的语义。多年来,我一直在我的 ASP.NET 项目中使用 Identity 以及我预先存在的数据库架构(没有角色表)。我承认,由于 ASP.NET Identity 的繁琐复杂性,以及 ASP.NET 中开源代码的快节奏变化,再加上完全缺乏人类知情的文档,理解如何做到这一点相当困难在 API 参考中(完全是机器生成的样板)。
在 ASP.NET Core 之前,您可以通过重写来做到这一点UserManager
and UserStore
实施。通过使用无操作来消除角色请求,或者覆盖RoleAttribute
使用更有用且对开发人员安全的实现(可能不是基于魔术字符串!),角色表的缺失不会被注意到。即使使用默认实现,如果您从未使用默认角色属性实现或询问角色问题,则可以删除表而不会产生任何后果。默认的 ASP.NET 脚手架都不依赖于角色。
在原始 ASP.NET Core Identity 1.0/1.1 版本中,您通过实现来做到这一点UserStore
没有可选的IUserRoleStore
界面。相关信息可以在主要 ASP.NET Core Identity 文档.
从 ASP.NET Core 2.0 开始(根据您的主要问题),您可以通过从以下内容派生上下文来更轻松地做到这一点IdentityUserContext
代替IdentityDbContext
,如下例所示。由于在 2.0 中不再需要自定义实现the new UserOnlyStore。致电给AddIdentity
Startup.cs 中也需要替换为AddIdentityCore. AddIdentityCore
如果您依赖其他标准身份验证功能,则需要几行额外的代码,因为默认情况下它不会初始化 Cookie 或 TokenProvider。 (如下所述,在 2.1 中,对样板进行了更改Startup
不再需要。)
在 ASP.NET Core 2.1/2.2(撰写本文时为当前版本)中删除角色非常简单。下面用一个新项目的例子来演示:
-
创建一个新项目来证明身份,选择:
- ASP.NET Core Web 应用程序项目类型
- Web 应用程序(任一类型,例如 MVC)
- 更改身份验证
- 个人用户帐户
- 在应用程序内存储用户帐户
-
从新搭建的 Identity 项目中删除角色
- edit Data\ApplicationDbContext.cs, elevating the context base class above roles
- from:
ApplicationDbContext : IdentityDbContext
- to:
ApplicationDbContext : IdentityUserContext<IdentityUser>
- 请注意,IdentityUserContext 需要一个 IdentityUser 泛型
- 由于 ASP.NET Core 2.1 中的新身份代码,这就是所需要的
-
请注意IdentityUserContext
缺少 Role,因此自定义键类型仅需要 2 个参数
- 在ApplicationDbContext.cs中:
IdentityUserContext<IdentityUser<int>, int>
- 在 Startup.cs 中,
AddDefaultIdentity<IdentityUser<int>>()
指定如前
- 提供给 _LoginPartial.cshtml 的模型也像以前一样指定。有关更改身份模型的更多详细信息
- if you've changed identity key type, the default EF Migration process fails
- 如果您更改了密钥,EF 会生成非功能性迁移
- simply deleting Data\Migrations works in test, with these caveats:
- 脚手架项目包含非默认索引
- 如果您已经运行该项目,则需要删除数据库
-
更新/构建数据库架构以反映上述内容。在包管理器控制台中:
Add-Migration RemoveIdentitySchemaRoles
Update-Database
运行应用程序
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)