了解 Asp.Net Identity 关键点 [英] Understanding Asp.Net Identity key points

查看:28
本文介绍了了解 Asp.Net Identity 关键点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am an Asp.net developer but very much new to the Asp.net Identity framework. I have been studying the sample application and followed some tutorials too on Identity but still I am not able to grasp the concept completely. I have very firm grip over Asp.net membership but Identity seems nothing like membership. I will explain what I have done so far.

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

I am creating a simple application in which I am following code first approach. I have created entity model for User which inherits from IdentityUser and has some extra fields. Below is entity model for 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; }
}

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

Now in the examples people use the name ApplicationUser but for my own purpose I have used name User. Also there is a method in User or ApplicationUser model which is,

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;
    }

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

I am unable to understand the purpose of this method. Also from an example I have used the following model for Role,

public class Role : IdentityRole
{
    public Role()
    {

    }

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

    public string Description { get; set; }
}

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

I understand that an extra field is added but I am unable to understand the purpose of overloaded constructor.

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

The above mentioned confusions are secondary. My primary confusion is that I am familiar that when I create entity models I use DbSet and DbContext and when I call any entity framework method to access the database, the database is created/drop created whichever scheme I am following.

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

In Identity which method is responsible for creating the Identity tables in the database? I have a IdentityConfig file in which I declare ApplicationUserManager and ApplicationSignInManager. I have also a Startup file. Previously I had only one Startup file in the App_Start folder and when I run the application and tried to accessed any Identity methods it gave me error and was not creating database. I then made the class as partial and created another partial class with same name at the root and then the exception was gone and tables were created. So Startup class is responsible for creating Identity tables? There are extra columns created automatically in the AspNetUsers like PhoneNumber, PhoneNumberConfirmed, TwoFactorEnabled. I don't need these extra columns. Can I remove these? Can I change the names of the Identity tables that are created?

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

I know these are very basic questions and not one question at all but if I was unable to find some basic tutorial or example for beginners then it would be very beneficial. What I have found are describing those things which I don't need or making me confuse. I want to understand and have control how Identity should work in my application but till now it seems to me that neither I am grasping it completely and nor being able to make is adjustable to my needs. Its like tutorials and example are teaching me how to make sentences but I am unable to understand the alphabets. :(

推荐答案

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

First of all you have to define the model - as you're doing - implementing the right interfaces.
Let's say you want to create a user for your application:

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

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

As you can see I've implemented the IdentityUser interface (namespace Microsoft.AspNet.Identity.EntityFramework).

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

I've specified what type of identifier I want to use for my primary key (string) and included my custom objects to manges login, roles and claims.

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

Now we can defined the role object:

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

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

Again there's a type and the class I've defined for the management of users belonging to to a role.

public class MyUserRole : IdentityUserRole<string>
{
}

MyUserLogin 将实现 IdentityUserLogin.
MyUserClaim 将实现 IdentityUserClaim.

MyUserLogin is going to implement IdentityUserLogin<string>.
MyUserClaim is going to implement IdentityUserClaim<string>.

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

As you can see each interface need a type for the primary key.

第二步是创建用户存储:

The second step is to create the user store:

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

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

Again we have defined what user, role, login etc etc we want to use.
We need UserStore cause our UserManager is going to need one.

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

If you're planning to manage roles and associate roles with each user you have to create your RoleStore definition.

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

现在您可以创建您的 UserManager.UserManager 是真正的负责保存对 UserStore 的更改.

Now you can create your UserManager. The UserManager is the real responsible of saving changes to the 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);
    }
}

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

This class has a static method which will create a new UserManager for you.
Interesting to note that you can include some validation rules you might need to validate password etc etc.

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

Last thing is to create or database context.

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");
    }
}

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

As you can see I've used the model builder to change the names all the tables. You can define keys or fields type or tables relations here.

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

This is the place where you're going to attach your custom classes you want to manage in your context:

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

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

Again MyContext has a Create method which returns a new context:

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

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

Now you should have a startup class where you're going to bootstrap your stuff:

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

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

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

Here you're going to create your database context and your user manager you can use in your application.

注意第一行:

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

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

This is needed cause you're telling your environment that is the startup class which needs to be called at ... startup.

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

Now in your controllers you can simply refer to your UserManager doing something like this:

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

如何创建表格?

在 Visual Studio 中,转到 TOOLS -> NuGet Packager Manager -> Package Manager Console.

In Visual Studio go to TOOLS -> NuGet Packager Manager -> Package Manager Console.

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

In the window there's a combobox "Default Project". Choose your ASP.NET MVC project.
Run this command:

Enable-Migrations

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

It will create a file Configuration.cs in a new folder called Migrations.
If you want to create your database you need to open that file and change the AutomaticMigrationsEnabled to true:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

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

Again, from Package Manager Console, you can run:

Update-Database

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

and all your tables will appear in your database. Don't forget your connection string.

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

You can download this github project to see how everything works.
You can check these two answers with some other info.

两者中的第一个有一些指向博客的链接,您可以在其中了解所有这些内容.

The first of the two has got some links to a blog where you can learn all these things.

注意:

如果您想自定义环境的每一点,您必须执行所有这些操作.

You have to do all this if you want to customized every single bit of your environment.

这篇关于了解 Asp.Net Identity 关键点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆