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

问题描述

我是一个Asp.net开发者,但很多新来的Asp.net身份框架。我一直在研究示例应用程序,并遵循一些教程上也认同,但仍然我不能完全把握的概念。我有超过Asp.net会员非常坚定的抓地力,但似乎身份没有像会员资格。我将解释什么我迄今所做的。

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.

我创建一个简单的应用程序中,我下面code第一种方法。我已经创建了用户从IdentityUser继承,并有一些额外的字段的实体模型。下面是用户实体模型。

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但对于我自己的目的我已经使用的用户名。也有在用户或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.

在身份,该方法是负责在数据库中创建的身份表?我有在我宣布ApplicationUserManager和ApplicationSignInManager一个IdentityConfig文件。我也是一个启动文件。 previously我在App_Start文件夹中只有一个启动文件,当我运行应用程序,并试图访问的任何标识方法它给了我的错误,并没有创建数据库。然后我的类部分,并在根目录中创建具有相同名称的另一部分类,然后异常消失了,表被创建。因此,启动类是负责创建标识表?还有像******中国,PhoneNumberConfirmed,TwoFactorEnabled的AspNetUsers自动创建额外的列。我不需要这些额外的列。我可以删除这些?我可以改变所创建的标识表的名称?

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?

我知道这些都是很基本的问题,而不是在所有的一个问题,但如果我无法找到适合初学者的基本教程或例子那么这将是非常有益的。我发现所描述的那些我不需要的东西还是让我迷惑。我想了解并控制如何标识应在我的应用程序工作,但直到现在,在我看来,无论我完全把握它,也能够使可调,以我的需求。它像教程和例子都教我如何使句子,但我无法理解的字母。 (

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 )。

我指定我想用我的主键(字符串)什么类型的标识符,其中包括我的自定义对象Manges律师登录,角色和索赔。

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&LT;字符串方式&gt; 结果
MyUserClaim 是要落实 IdentityUserClaim&LT;串GT;

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 已返回一个新的上下文中的创建方法:

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>();

你怎么能创建表?

How can you create your tables?

在Visual Studio中去工具 - >包装的NuGet管理器 - >软件包管理器控制台

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

这将创建一个名为新文件夹迁移文件 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;
}

再次从软件包管理器控制台,您可以运行:

Update-Database

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

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

您可以下载这个看到的一切是如何工作的。结果
您可以检查这些two answers与其他一些信息。

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

的first两人已经得到了一些链接到一个博客,你可以学习所有这些事情。

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身份的关键点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:02