ASP.NET MVC: Custom Login form & Registration form
By Tan Lee Published on May 29, 2017 13.1K
How to Custom Login Form, Registration Form with ASP.NET Identity MVC 5 using C#, Entity Framework Code First
Step 1: Open IdentityConfig class, then you can configure validation password as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base (store) { //PasswordHasher = new CustomPasswordHasher(); } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager( new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false , RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false , RequireDigit = false , RequireLowercase = false , RequireUppercase = false , }; // 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 it in here. manager.RegisterTwoFactorProvider( "Phone Code" , new PhoneNumberTokenProvider<ApplicationUser> { MessageFormat = "Your security code is {0}" }); manager.RegisterTwoFactorProvider( "Email Code" , new EmailTokenProvider<ApplicationUser> { Subject = "Security Code" , 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<ApplicationUser>(dataProtectionProvider.Create( "ASP.NET Identity" )); } return manager; } } |
Open AccountViewModels class, then change LoginViewModel and RegisterViewModel allows you to create and login with a usename
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class LoginViewModel { //[Required] [Display(Name = "Email" )] [EmailAddress] public string Email { get ; set ; } [Display(Name = "User Name" )] [Required] public string UserName { get ; set ; } [Required] [DataType(DataType.Password)] [Display(Name = "Password" )] public string Password { get ; set ; } [Display(Name = "Remember me?" )] public bool RememberMe { get ; set ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email" )] public string Email { get ; set ; } [Display(Name = "User Name" )] public string UserName { get ; set ; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long." , MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password" )] public string Password { get ; set ; } [DataType(DataType.Password)] [Display(Name = "Confirm password" )] [Compare( "Password" , ErrorMessage = "The password and confirmation password do not match." )] public string ConfirmPassword { get ; set ; } } |
Open AccountController, then change Register and Login action as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false , rememberBrowser: false ); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction( "Index" , "Home" ); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false ); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View( "Lockout" ); case SignInStatus.RequiresVerification: return RedirectToAction( "SendCode" , new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default : ModelState.AddModelError( "" , "Invalid login attempt." ); return View(model); } } |
Open Register and Login view, then change Email to Username
VIDEO TUTORIALS
- ASP.NET MVC Responsive Templates Free Download
- How to upload file in ASP.NET MVC
- How to Create Contact Form Flat Responsive in ASP.NET MVC
- How to check if HttpPostedFileBase is an image
- How to upload Multiple File in ASP.NET MVC
- ASP.NET MVC: Implement Password Reset with ASP NET Identity
- ASP.NET MVC: Getting Started
- ASP.NET MVC: Create Custom Routes
Categories
Popular Posts
How to secure ASP.NET Core with NWebSec
Nov 07, 2024
Admin BSB Free Bootstrap Admin Dashboard
Nov 14, 2024
Freedash bootstrap lite
Nov 13, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024