Understanding Asp.Net Identity Keywords

I am an Asp.net developer but very new to the Asp.net Identity framework. I have studied the sample application and followed some tutorials also in Identity, but still I cannot fully understand the concept. I have a very strong bond with Asp.net membership, but Identity doesn't feel like membership. I will explain what I have done so far.

I am creating a simple application in which I follow the first code approach. I have created an Object Model for User which inherits from IdentityUser and has some additional fields. Below is the model of the object for the 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 ApplicationUser name, but for my own purpose I used User name. There is also a method in the User or ApplicationUser model which,

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 cannot understand the purpose of this method. Also from the example I used the following model for the 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 has been added, but I cannot understand the purpose of the overloaded constructor.

The aforementioned confusion is secondary. My main confusion is that I am familiar with the fact that when I create entity models I use DbSet and DbContext and when I call any method of entity framework to access the database, the database is created / dropped no matter what the diagram I am following.

In Identity, which method is responsible for creating the Identity tables in the database? I have an IdentityConfig file in which I declare ApplicationUserManager and ApplicationSignInManager. I also have an autoload file. Previously, I only had one startup file in the App_Start folder, and when I ran the application and tried to access any authentication methods, it gave me an error and didn't create the database. Then I made the class incomplete and created another incomplete class with the same name at the root, and then the exception was gone and the tables were created. So the Startup class is responsible for creating the Identity tables? Additional columns are automatically created in AspNetUsers such as PhoneNumber, PhoneNumberConfirmed, TwoFactorEnabled. I don't need these extra columns. Can I delete them? Can I change the names of the generated Identity tables?

I know these are very simple questions, not one question, but if I could not find a basic tutorial or example for beginners then it would be very helpful. What I found describes the things that I don't need or that I am confused about. I want to understand and control how Identity is supposed to work in my application, but so far it seems to me that I do not fully understand it and cannot do it since it suits my needs. Its like tutorials and example teaches me to make sentences, but I cannot understand the alphabets. :(

+3


source to share


1 answer


First of all, you must define a model - how you do it - implementation of the correct 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 have implemented an interface IdentityUser

( Microsoft.AspNet.Identity.EntityFramework namespace ).

I have specified what type of id I want to use for my primary key (strings) and have included my custom objects to manage entries, roles and claims.

Now we can define the role object:

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

      

Again, the type and class that I have defined to manage the users belonging to the role.

public class MyUserRole : IdentityUserRole<string>
{
}

      

MyUserLogin

going to implement IdentityUserLogin<string>

.
MyUserClaim

going to implement IdentityUserClaim<string>

.

As you can see, each interface needs a primary key type.

The second step is to create a user store:

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

      

Again we have determined which user, role, login, etc. etc. we want to use.
We need to UserStore

get our UserManager to be needed.

If you plan to manage roles and associate roles with each user, you need to create a definition RoleStore

.

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

      

Now you can create your own UserManager

. UserManager is the real person responsible for saving changes to 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 that will create a new UserManager for you.
It is interesting to note that you can enable some validation rules that might be required to confirm a password, etc.

The last thing is the creation or context of the database.

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 used the constructor model to change the names of all tables. Here you can define the types of keys or fields of type or table.

This is where you are going to attach your custom classes that you want to manage in your context:

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

      



Again MyContext

has a method Create

that returns a new context:

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

      

You should now have a launch class where you are going to load 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);
        }
    }
}

      

This is where you are going to create your database context and your custom manager that you can use in your application.

Pay attention to the first line:

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

      

This is necessary because you are telling your environment which is the startup class to be called at startup.

Now, in your controllers, you can simply reference yours by UserManager

doing something like this:

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

      

How can you create your tables?

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

In the window there is a combobox "Project by default". Select your ASP.NET MVC project.
Run this command:

Enable-Migrations

      

It will create a file Configuration.cs

in a new folder named Migrations

.
If you want to create your database, you need to open this file and change 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 to include the connection string.

You can download this github project to see how it works.
You can check these two answers with other information.

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

Note:

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

+8


source







All Articles