了解Asp.Net Identity关键点

Adn*_*een 3 entity-framework-6 asp.net-mvc-5 asp.net-identity-2

我是Asp.net开发人员,但对Asp.net Identity框架非常陌生.我一直在研究示例应用程序,并且在Identity上也遵循了一些教程,但我仍然无法完全掌握这个概念.我非常坚定地掌握Asp.net会员资格,但身份似乎与会员资格无关.我会解释到目前为止我做了什么.

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

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

    public bool? CanWork { get; set; }

    public bool? CanSearch { get; set; }

    public Company Company { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在在示例中,人们使用名称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;
    }
Run Code Online (Sandbox Code Playgroud)

我无法理解这种方法的目的.同样从一个例子我使用以下模型的角色,

public class Role : IdentityRole
{
    public Role()
    {

    }

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

    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

上述混淆是次要的.我的主要困惑是我熟悉当我创建实体模型时,我使用DbSet和DbContext,当我调用任何实体框架方法来访问数据库时,无论我遵循哪种方案,都会创建/删除数据库.

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

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

Lef*_*tyX 8

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

public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public string CompanyName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我已经实现了IdentityUser接口(名称空间Microsoft.AspNet.Identity.EntityFramework).

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

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

public class MyRole : IdentityRole<string, MyUserRole>
{
}
Run Code Online (Sandbox Code Playgroud)

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

public class MyUserRole : IdentityUserRole<string>
{
}
Run Code Online (Sandbox Code Playgroud)

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

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

第二步是创建用户存储:

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

我们再次定义了我们想要使用的用户,角色,登录等.
我们需要UserStore因为我们的UserManager需要一个.

如果您计划管理角色并将角色与每个用户关联,则必须创建RoleStore定义.

public class MyRoleStore : RoleStore<MyRole, string, MyUserRole>
{
    public DaufRoleStore(ApplicationDatabaseContext context) : base(context)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以创建你的UserManager.UserManager是保存更改的真正责任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);
    }
}
Run Code Online (Sandbox Code Playgroud)

该类有一个静态方法,它将为您创建一个新的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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这是您要在上下文中附加要管理的自定义类的位置:

public DbSet<MyCustomer> Customers{ get; set; }
Run Code Online (Sandbox Code Playgroud)

再次MyContext有一个Create返回新上下文的方法:

public static MyContext Create()
{
    return new MyContext();
}
Run Code Online (Sandbox Code Playgroud)

现在你应该有一个启动类,你要引导你的东西:

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

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

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

注意第一行:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]
Run Code Online (Sandbox Code Playgroud)

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

现在在您的控制器中,您可以简单地参考您UserManager执行的操作:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Run Code Online (Sandbox Code Playgroud)

你怎么能创建你的表?

在Visual Studio中,转到工具 - > NuGet Packager Manager - >包管理器控制台.

在窗口中有一个组合框"默认项目".选择您的ASP.NET MVC项目.
运行此命令:

Enable-Migrations
Run Code Online (Sandbox Code Playgroud)

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

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}
Run Code Online (Sandbox Code Playgroud)

再次,Package Manager Console你可以运行:

Update-Database
Run Code Online (Sandbox Code Playgroud)

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

您可以下载此github项目以查看一切是如何工作的.
您可以使用其他一些信息检查这两个 答案.

这两个中的第一个有一些链接到博客,你可以学习所有这些东西.

注意:

如果要自定义环境的每一个位,就必须完成所有这些操作.

  • 很高兴我在某种程度上帮助过.祝好运.我并不特别喜欢那些混乱,但这就是它的工作方式.干杯. (2认同)