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?
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
Getting Current UserName in Controller Getting UserName in Controller is easy as you can directly access the HttpContext object within Controller. You need to access HttpContext.User.Identity.Name property to access the username.
Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.
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 :
Modify the Register.cshtml.cs
, add Username to InputModel
:
[Required]
[DataType(DataType.Text)]
[Display(Name = "User Name")]
public string UserName { get; set; }
Modify the OnPostAsync
method :
var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
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>
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; }
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>
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With