Documentation

Initialize ASP.NET Identity

You can initialize ASP.NET Identity when the application starts. Since ASP.NET Identity is Entity Framework based in this sample, you can create DatabaseInitializer which is configured to get called each time the app starts.

Please check ApplicationDbInitializer class inApp_Start\IdentityConfig.cs

This code shows the following
  • When should the Initializer run and when should the database be created
  • Create Admin user
  • Create Admin role
  • Add Admin user to Admin role
    public class ApplicationDbInitializer : DropCreateDatabaseAlways
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeIdentityForEF(context);
            base.Seed(context);
        }

        //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
        public static void InitializeIdentityForEF(ApplicationDbContext db)
        {
            var userManager = HttpContext.Current.GetOwinContext().GetUserManager();
            var roleManager = HttpContext.Current.GetOwinContext().Get();
            const string name = "admin@example.com";
            const string password = "Admin@123456";
            const string roleName = "Admin";

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new ApplicationRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);

            }

            var groupManager = new ApplicationGroupManager();
            var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");

            groupManager.CreateGroup(newGroup);
            groupManager.SetUserGroups(user.Id, new string[] { newGroup.Id });
            groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
        }
    }
        

Customizing User's Profile Information

Please follow this tutorial to learn more about:
  • Add profile information in the ApplicationUser class
  • Add migration and update database

Validation

When you create a User using a username or password, the Identity system performs validation on the username and password, and the passwords are hashed before they are stored in the database. You can customize the validation by changing some of the properties of the validators such as Turn alphanumeric on/off, set minimum password length or you can write your own custom validators and register them with the UserManager.

        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore(context.Get()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
        }

        

Adding Social Logins

ASP.NET Identity enables users to log in using OAuth 2.0 with credentials from an external authentication provider, such as Facebook, Twitter, LinkedIn, Microsoft, or Google. For simplicity, this tutorial focuses on working with credentials from Facebook and Google.

Enabling these credentials in your web sites provides a significant advantage because millions of users already have accounts with these external providers. These users may be more inclined to sign up for your site if they do not have to create and remember a new set of credentials.

User Management

Do Create, Update, List and Delete Users. Assign a Role to a User. Only Users In Role Admin can access this page. This uses the on the UserAdmin controller.

Role Management

Perform Create, Update, List and Delete role.

Group Management

  • Perform Create, Update, List and Delete Groups.
  • Assign roles to one or more group.

Log in, Email Confirmation and Password Reset

This tutorial shows you how to build an ASP.NET MVC 5 web app with email confirmation and password reset using the ASP.NET Identity membership system.

Two-Factor Authentication

This tutorial shows you how to build an ASP.NET MVC 5 web app with Two-Factor Authentication.

        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore(context.Get()));
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug in here.
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider
            {
                Subject = "SecurityCode",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
        

Account Lockout

Provide a way to Lockout out the user if the user enters their password or two-factor codes incorrectly. The number of invalid attempts and the timespan for the users are locked out can be configured. A developer can optionally turn off Account Lockout for certain user accounts should they need to.
        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore(context.Get()));
            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug in here.
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider
            {
                MessageFormat = "Your security code is: {0}"
            });