Introduction
In this article, I will discuss how to create registration and login functionalities in ASP.NET Core web applications using Identity. ASP.NET Core Identity is an API that supports login functionality in ASP.NET Core MVC web application. Login information can be stored in identity when creating a new user account. Identity can be configured with SQL Server database to store user details such as username, password, and email id. So in this article, I will explain how to use identity to register, login and logout of a user account.
ViewModel SignIn
public class SignInVM {
[Required]
public string UsernameOrEmail {
get;
set;
}
[Required, DataType(DataType.Password)]
public string Password {
get;
set;
}
public bool RememberMe {
get;
set;
}
}
ViewModel Register
public class RegisterVM {
[Required, MaxLength(50)]
public string Username {
get;
set;
}
[Required, DataType(DataType.EmailAddress)]
public string Email {
get;
set;
}
[Required, DataType(DataType.Password)]
public string Password {
get;
set;
}
[DataType(DataType.Password), Compare(nameof(Password))]
public string ConfirmPassword {
get;
set;
}
}
Auth Controller
public class AuthController: Controller {
private readonly UserManager < AppUser > _userManager;
private readonly SignInManager < AppUser > _signInManager;
private RoleManager < IdentityRole > _roleManager {
get;
}
public AuthController(UserManager < AppUser > userManager, SignInManager < AppUser > signInManager, RoleManager < IdentityRole > roleManager) {
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
}
public IActionResult SignIn() {
return View();
}
[HttpPost]
public async Task < IActionResult > SignIn(SignInVM signIn, string ReturnUrl) {
AppUser user;
if (signIn.UsernameOrEmail.Contains("@")) {
user = await _userManager.FindByEmailAsync(signIn.UsernameOrEmail);
} else {
user = await _userManager.FindByNameAsync(signIn.UsernameOrEmail);
}
if (user == null) {
ModelState.AddModelError("", "Login ve ya parol yalnisdir");
return View(signIn);
}
var result = await
_signInManager.PasswordSignInAsync(user, signIn.Password, signIn.RememberMe, true);
if (!result.Succeeded) {
ModelState.AddModelError("", "Login ve ya parol yalnisdir");
return View(signIn);
}
if (ReturnUrl != null) return LocalRedirect(ReturnUrl);
return RedirectToAction("Index", "Team", new {
area = "admin"
});
}
public IActionResult Register() {
return View();
}
[HttpPost]
public async Task < IActionResult > Register(RegisterVM register) {
if (!ModelState.IsValid) return View();
AppUser newUser = new AppUser {
Email = register.Email,
UserName = register.Username
};
IdentityResult result = await _userManager.CreateAsync(newUser, register.Password);
if (!result.Succeeded) {
foreach(var item in result.Errors) {
ModelState.AddModelError("", item.Description);
}
}
return RedirectToAction("SignIn");
}
public async Task < IActionResult > SignOut() {
await _signInManager.SignOutAsync();
return RedirectToAction(nameof(SignIn));
}
}
AppDbContext
public class AppDbContext: IdentityDbContext < AppUser > {
public AppDbContext(DbContextOptions < AppDbContext > options): base(options) {}
public DbSet < Team > Teams {
get;
set;
}
}
Models>AppUser
public class AppUser: IdentityUser {
public string Name {
get;
set;
}
}
Startup ConfigureServices
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
services.AddDbContext < AppDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddIdentity < AppUser, IdentityRole > ().AddEntityFrameworkStores < AppDbContext > ().AddDefaultTokenProviders();
services.Configure < IdentityOptions > (opt => {
opt.Password.RequiredLength = 6;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireDigit = true;
opt.Password.RequireLowercase = true;
opt.Password.RequireUppercase = false;
opt.User.RequireUniqueEmail = true;
opt.Lockout.MaxFailedAccessAttempts = 3;
opt.Lockout.DefaultLockoutTimeSpan = System.TimeSpan.FromMinutes(10);
});
services.AddHttpContextAccessor();
services.ConfigureApplicationCookie(options => {
options.LoginPath = "/Auth/SignIn";
});
}
Startup Configure method
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
Register View
Innocent LangaPosted Jun 27, 2022, 7:27 AM
Exactly what i was looking for. Where does public DbSet < Product > Products { get; set; } Come from