35

Whenever I create a new application with visual studio 2013 express for web and using the individual accounts authentication and i hit the register button I notice that it implements 'Email' instead of 'Username' and the same is in the LoginViewModel as it uses Email to Sign in instead of Username. How can i change this to use Username instead of the default Email without trouble? Also i would like to know how to convert the default 'guid' that is a string type to 'id' (integer type).

ibnhamza
  • 861
  • 1
  • 15
  • 29
  • [Here](http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity) is a very good article you can follow and you will get the answer. Also see this [question](http://stackoverflow.com/questions/19758575/asp-net-identity-use-email-instead-of-user-name) You can use your own usermanager class and use username instead of email. – Mairaj Ahmad Dec 16 '14 at 10:45
  • 2
    By default the code is using email as user name. `var user = new ApplicationUser { UserName = model.Email, Email = model.Email };`. Add userName property to RegisterViewModel and use it instead. – LCJ Jan 19 '17 at 17:09

4 Answers4

43

The linked question in the accepted answer descibes how to use Email instead of UserName, OP wanted the UserName instead of email which is what I was looking for in Identity 2.0 in an MVC project.

In case anyone else gets here from a google search it is actually very easy to do this. If you look at the register post action it is simply setting the UserName to the Email address. So.........

Add UserName to the RegisterViewModel and add it to the register view.

<div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "Username or email" })
        </div>
</div>

In the Register Post Action on the AccountController set the UserName to the ViewModel's UserName and the Email to the ViewModel's Email.

var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
Hoody
  • 3,361
  • 9
  • 45
  • 55
  • I don't want to use email in any way. Is there any way that I can register without providing email address? – Yauvaraj Rimal Mar 05 '15 at 08:44
  • I don't know if the email address is mandatory in the model but if it's not you could remove the four lines in the registration view for the email address and replace them with the UserName code I have listed above. Then you could set the new ApplicationUser as follows in the post action in your AccountController. var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; If the email address is mandatory just set the email to string.empty – Hoody Mar 05 '15 at 10:08
  • Validation checks for string.Empty. sasi kumar's answer works correctly. – Brian P Jun 04 '16 at 18:15
  • made the same, but registration doens't work because Username in RegisterViewModel is still null – TheQult Mar 07 '17 at 18:33
24

In order to make email as non unique:

Configure below in IdentityConfig

manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = false                
            };
sasi kumar
  • 241
  • 2
  • 3
0

Please look into this thread

Thread Details :

Assumptions:

  1. Username is unique for each user. It is either input by user or generated by application on registration.
  2. No @ symbol allowed in Username.

Remove EmailAddress annotation and define Display text in the default LoginViewModel:

public class LoginViewModel
{
    [Required]
    [Display(Name = "Username/Email")]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

As user can enter either Username or Email, so we will make @ character for validation criteria. Here is the flow to be implemented:

  1. If in the string @ is present, apply Email validation else apply Username format validation.
  2. In case of valid Email, first we need to get Username. As it is considered that Username is unique so we can get it with userManager.FindByEmailAsync method.
  3. Use Username for SignIn verification.

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
       ViewData["ReturnUrl"] = returnUrl;
       if (model.Email.IndexOf('@') > -1)
       {
           //Validate email format
           string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                              @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
           Regex re = new Regex(emailRegex);
           if (!re.IsMatch(model.Email))
           {
               ModelState.AddModelError("Email", "Email is not valid");
           }
       }
       else
       {
           //validate Username format
           string emailRegex = @"^[a-zA-Z0-9]*$";
           Regex re = new Regex(emailRegex);
           if (!re.IsMatch(model.Email))
           {
               ModelState.AddModelError("Email", "Username is not valid");
           }
       }
    
       if (ModelState.IsValid)
       {
           var userName = model.Email;
           if (userName.IndexOf('@') > -1)
           {
               var user =  await _userManager.FindByEmailAsync(model.Email);
               if (user == null)
               {
                   ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                   return View(model);
               }
               else
               {
                    userName = user.UserName;
               }
            }
            var result = await _signInManager.PasswordSignInAsync(userName, model.Password, model.RememberMe, lockoutOnFailure: false);
    

No special need to change in View. Run the application and test login with Email or Username.

Note: Keep in mind this tutorial follows MVC .Net Identity default structure.

Faraz Ahmed
  • 1,467
  • 2
  • 18
  • 33
0

You can also use username and/or password like this

var user = await _userManager.Users
       .FirstOrDefaultAsync(u => u.UserName == username || u.Email == username);

if (user != null){
var result = await _signInManager
            .PasswordSignInAsync(user.Email, password, false, false);
}
Bellash
  • 7,560
  • 6
  • 53
  • 86