Search code examples
asp.netasp.net-core

ASP.NET Core : How to login with “UserName” instead of “Email”?


With asp.net core, all the login pages and viewmodels etc are hidden in referenced packages, so can't be directly changed. How do I allow login to still make use of usernames and not force the use of emails?


Solution

  • The first step is to scaffold identity to your application :

    Scaffold Identity in ASP.NET Core projects

    Then you could customize the Register.cshtml/Register.cshtml.cs and Login.cshtml/Login.cshtml.cs , update model and view , and change the logic in OnPostAsync function to fit your requirement .

    To your requirement , you can follow the steps :

    1. Scaffold identity into your project .
    2. Modify the Register.cshtml.cs , add Username to InputModel :

      [Required]
      [DataType(DataType.Text)]
      [Display(Name = "User Name")]
      public string UserName { get; set; }
      
    3. Modify the OnPostAsync method :

      var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
      
    4. Update the Register.cshtml to include the UserName :

      <div class="form-group">
          <label asp-for="Input.UserName"></label>
          <input asp-for="Input.UserName" class="form-control"/>
          <span asp-validation-for="Input.UserName" class="text-danger"></span>
      </div>
      
    5. Modify the Login.cshtml.cs , modify InputModel to replace Email with UserName :

      [Required]
      [DataType(DataType.Text)]
      [Display(Name = "User Name")]
      public string UserName { get; set; }
      
    6. Modify the Login.cshtml :

      <div class="form-group">
          <label asp-for="Input.UserName"></label>
          <input asp-for="Input.UserName" class="form-control" />
          <span asp-validation-for="Input.UserName" class="text-danger"></span>
      </div>
      
    7. Modify the Login.cshtml.cs OnPostAsync method to use Username instead of email :

      var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
      

    By default ASP.NET Identity uses FindByNameAsync to check if user with given name exists , so that you don't need to override PasswordSignInAsync function in SignInManager . If you want to login with email , your could click here to update that .