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

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

问题描述

我是Asp.net开发人员,但对Asp.net身份框架来说非常新鲜。我一直在研究示例应用程序,并遵循一些关于身份的教程,但是我仍然无法完全掌握这个概念。我对Asp.net会员非常坚定,但身份似乎不是会员资格。我将解释我迄今为止做了什么。



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

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

public bool? CanWork {get;组; }

public bool? CanSearch {get;组; }

public公司公司{get;组; }
}

在示例中,人们使用ApplicationUser命名,但是为了我自己的目的使用了用户名。在User或ApplicationUser模型中也有一种方法,它是

  public async Task< ClaimsIdentity> GenerateUserIdentityAsync(UserManager< User> manager)
{
CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
//在此添加自定义用户声明
return userIdentity;
}

我无法理解此方法的目的。另外从一个例子我已经使用以下模型的角色,

  public class角色:IdentityRole 
{
public Role()
{

}

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

public string说明{get;组; }
}

我明白添加了一个额外的字段,但我无法理解超负荷构造函数的目的。



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



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



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

解决方案

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

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

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

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



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

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

再次有一个类型和类I为m定义管理属于角色的用户。

  public class MyUserRole:IdentityUserRole< string> 
{
}

MyUserLogin 将实现 IdentityUserLogin< string>

MyUserClaim 将要实现 IdentityUserClaim<串GT;



您可以看到每个接口需要一个主键的类型。



第二步是创建用户商店:

  public 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是真正的负责人将更改保存到 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为您。

有趣的是,您可以包括一些验证规则,您可能需要验证密码等。



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

  public class MyContext:IdentityDbContext< MyUser,MyRole,string,MyUserLogin,MyUserRole,MyUserClaim> 
{
public MyContext():base(<你的连接字符串在这里>)
{

}

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

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



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

  public DbSet< MyCustomer>客户{get;组; } 

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

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

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

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

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

创建数据库上下文和您可以在应用程序中使用的用户管理器。注意第一行:

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

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



现在在控制器中,您可以直接参考 UserManager 做这样的事情:

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

如何创建表?



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



在窗口中有一个组合框默认项目。选择您的ASP.NET MVC项目。

运行此命令:

 启用迁移

它将在新文件夹中创建一个文件 Configuration.cs 调用迁移

如果要创建数据库,需要打开该文件并更改 AutomaticMigrationsEnabled to true:

  public Configuration()
{
AutomaticMigrationsEnabled = true;
}

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

 更新数据库

,所有的表都会显示在您的数据库中。不要忘记你的连接字符串。



您可以下载 github项目查看一切如何工作。

您可以检查这些两个 answer 与其他一些信息。



第一个已经有一些链接到一个博客,你可以学习所有这些事情。



注意:



如果您要自定义你的环境的每一点。


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.

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

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.

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.

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

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 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)
    {
    }
}

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.

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)
    {
    }
}

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

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

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.

Notice the first line:

[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.

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?

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

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

Enable-Migrations

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

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.

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.

NOTE:

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

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

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