了解 Asp.Net 身份关键点

Understanding Asp.Net Identity key points

我是一名 Asp.net 开发人员,但对 Asp.net Identity framework 非常陌生。我一直在研究示例应用程序并遵循一些关于身份的教程,但我仍然无法完全掌握这个概念。我对 Asp.net 会员资格有非常坚定的控制,但身份似乎与会员资格完全不同。我将解释到目前为止我所做的事情。

我正在创建一个简单的应用程序,我在其中遵循代码优先方法。我为 User 创建了实体模型,它继承自 IdentityUser 并且有一些额外的字段。下面是用户的实体模型。

public class User : IdentityUser
{
    public int? CompanyID { get; set; }

    public bool? CanWork { get; set; }

    public bool? CanSearch { get; set; }

    public Company Company { get; set; }
}

现在在示例中,人们使用名称 ApplicationUser,但为了我自己的目的,我使用了名称 User。在 User 或 ApplicationUser 模型中也有一个方法,

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
    {
        CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

我无法理解此方法的用途。同样从一个示例中,我使用了以下角色模型,

public class Role : IdentityRole
{
    public Role()
    {

    }

    public Role(string roleName, string description)
        : base(roleName)
    {
        this.Description = description;
    }

    public string Description { get; set; }
}

我知道添加了一个额外的字段,但我无法理解重载构造函数的目的。

上述混淆是次要的。我的主要困惑是我很熟悉,当我创建实体模型时,我使用 DbSet 和 DbContext,当我调用任何 entity framework 方法来访问数据库时,数据库是 created/drop 创建的,无论我遵循哪个方案。

在 Identity 中,哪个方法负责在数据库中创建 Identity 表?我有一个 IdentityConfig 文件,我在其中声明了 ApplicationUserManager 和 ApplicationSignInManager。我还有一个启动文件。以前我在 App_Start 文件夹中只有一个启动文件,当我 运行 应用程序并尝试访问任何 Identity 方法时,它给我错误并且没有创建数据库。然后我将 class 设为部分并在根目录下创建了另一个具有相同名称的部分 class 然后异常消失并创建了表。所以 Startup class 负责创建 Identity 表?在 AspNetUsers 中自动创建了额外的列,如 PhoneNumber、PhoneNumberConfirmed、TwoFactorEnabled。我不需要这些额外的列。我可以删除这些吗?我可以更改创建的身份表的名称吗?

我知道这些是非常基本的问题,根本不是一个问题,但如果我找不到一些适合初学者的基本教程或示例,那将是非常有益的。我发现的是描述那些我不需要或让我感到困惑的东西。我想了解并控制 Identity 在我的应用程序中的工作方式,但到目前为止,在我看来,我既没有完全掌握它,也无法根据我的需要进行调整。它就像教程和示例一样教我如何造句,但我无法理解字母表。 :(

首先,您必须定义模型 - 正如您所做的那样 - 实现正确的接口。
假设您想为您的应用程序创建一个用户:

public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public string CompanyName { get; set; }
}

如您所见,我已经实现了 IdentityUser 接口(命名空间 Microsoft.AspNet.Identity.EntityFramework)。

我已经指定了我要用于我的主键(字符串)的标识符类型,并将我的自定义对象包含在管理登录、角色和声明中。

现在我们可以定义角色对象了:

public class MyRole : IdentityRole<string, MyUserRole>
{
}

还有一个类型和 class 我为属于某个角色的用户的管理定义的。

public class MyUserRole : IdentityUserRole<string>
{
}

MyUserLogin 将实施 IdentityUserLogin<string>.
MyUserClaim 将实施 IdentityUserClaim<string>

如您所见,每个接口都需要一个主键类型。

第二步是创建用户存储:

public class MyUserStore:  UserStore<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public MyUserStore(MyContext context)
        : base(context)
    {
    }
}

我们再次定义了我们要使用的用户、角色、登录名等。
我们需要 UserStore 因为我们的 UserManager 将需要一个。

如果您打算管理角色并将角色与每个用户相关联,您必须创建 RoleStore 定义。

public class MyRoleStore : RoleStore<MyRole, string, MyUserRole>
{
    public DaufRoleStore(ApplicationDatabaseContext context) : base(context)
    {
    }
}

现在您可以创建您的 UserManager。 UserManager 是真正的 responsible 将更改保存到 UserStore

public class ApplicationUserManager : UserManager<MyUser, string>
{
    public ApplicationUserManager(IUserStore<MyUser, string> store)
        : base(store)
    {

    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyContext>()));

        manager.UserValidator = new UserValidator<MyUser, string>(manager)
        {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
        };

        manager.PasswordValidator = new PasswordValidator()
        {
        RequiredLength = 5,
        RequireNonLetterOrDigit = false,     // true
        // RequireDigit = true,
        RequireLowercase = false,
        RequireUppercase = false,
        };

        return (manager);
    }
}

这个 class 有一个静态方法,可以为您创建一个新的 UserManager。
有趣的是,您可以包含一些您可能需要验证密码等的验证规则。

最后一件事是创建或数据库上下文。

public class MyContext : IdentityDbContext<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public MyContext(): base("<your connection string here>")
    {

    }

    public static MyContext Create()
    {
        return new MyContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<MyUser>()
            .ToTable("Users");

        modelBuilder.Entity<MyRole>()
            .ToTable("Roles");

        modelBuilder.Entity<MyUserRole>()
            .ToTable("UserRoles");

        modelBuilder.Entity<MyUserClaim>()
            .ToTable("UserClaims");

        modelBuilder.Entity<MyUserLogin>()
            .ToTable("UserLogins");
    }
}

如您所见,我已经使用模型生成器更改了所有表的名称。 您可以在此处定义键或字段类型或表关系。

这是您要附加要在上下文中管理的自定义 classes 的地方:

public DbSet<MyCustomer> Customers{ get; set; }

同样 MyContext 有一个 Create 方法,它 returns 一个新的上下文:

public static MyContext Create()
{
    return new MyContext();
}

现在你应该有一家初创企业 class,你将在那里 bootstrap 你的东西:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

namespace ASPNETIdentity2
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(MyContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        }
    }
}

在这里您将创建您的数据库上下文和您可以在您的应用程序中使用的用户管理器。

注意第一行:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

这是必需的,因为您要告诉您的环境这是需要在...启动时调用的启动 class。

现在在你的控制器中,你可以简单地参考你的 UserManager 做这样的事情:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

如何创建表格?

在 Visual Studio 中转到工具 -> NuGet 打包程序管理器 -> 程序包管理器控制台。

在 window 中有一个组合框 "Default Project"。选择您的 ASP.NET MVC 项目。
运行 这个命令:

Enable-Migrations

它将在名为 Migrations 的新文件夹中创建文件 Configuration.cs
如果您想创建数据库,您需要打开该文件并将 AutomaticMigrationsEnabled 更改为 true:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

同样,从 Package Manager Console,您可以 运行:

Update-Database

您的所有表格都将出现在您的数据库中。不要忘记您的连接字符串。

您可以下载此 github project 以查看一切如何工作。
您可以检查这些 answers 和一些其他信息。

两人的 获得了一些指向博客的链接,您可以在其中了解所有这些内容。

注意:

如果您想自定义环境的每一部分,则必须执行所有这些操作。