Understanding Asp.Net Identity key points

后端 未结 1 1185
清歌不尽
清歌不尽 2021-01-14 08:28

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 st

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 09:14

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

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

    MyUserLogin is going to implement IdentityUserLogin.
    MyUserClaim is going to implement IdentityUserClaim.

    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
    {
        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
    {
        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
    {
        public ApplicationUserManager(IUserStore store)
            : base(store)
        {
    
        }
    
        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new MyUserStore(context.Get()));
    
            manager.UserValidator = new UserValidator(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
    {
        public MyContext(): base("")
        {
    
        }
    
        public static MyContext Create()
        {
            return new MyContext();
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity()
                .ToTable("Users");
    
            modelBuilder.Entity()
                .ToTable("Roles");
    
            modelBuilder.Entity()
                .ToTable("UserRoles");
    
            modelBuilder.Entity()
                .ToTable("UserClaims");
    
            modelBuilder.Entity()
                .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 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.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();
    

    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.

    0 讨论(0)
提交回复
热议问题