In this Article we will learn How to Create Registration and Login using Identity in Asp.Net Core.
Prerequisites
- Download and install .Net Core 6.0 SDK from here
- Download and Install Microsoft Visual Studio 2022 from here
Create ASP.NET Core Web App
- Open visual studio and click the Create New Project Option
- Select the Blank Template
- Enter the name of the Project
Select framework and Click on Create
Install NuGet Packages
- Microsoft.AspNetCore.Identity.EntityFramework
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.InMemory
DbContext Class
DbContext Class. The DbContext is used for accessing application data through Entity Framework Core. You need to create DbContext class that derives from “IdentityDbContext” class
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Auth_Identity_Login.Services { //Identity contains all user table to inherits public class AppDbContext : IdentityDbContext { public AppDbContext(DbContextOptions<AppDbContext> option) :base(option) { } } }
Create View Model
using System.ComponentModel.DataAnnotations; namespace Auth_Identity_Login.Models { public class UserViewModel { [Key] public int userid { get; set; } public string username { get; set; } public string Email { get; set; } public string password { get; set; } } }
Program.cs
using Auth_Identity_Login.Services; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<AppDbContext>(config=> { config.UseInMemoryDatabase("Memory"); }); builder.Services.AddIdentity<IdentityUser, IdentityRole>(config=> { config.Password.RequiredLength = 5; config.Password.RequireDigit = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; }) .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); builder.Services.ConfigureApplicationCookie(config => { config.Cookie.Name = "Auth_Tutorial"; config.LoginPath = "/Home/Login"; }); builder.Services.AddMvc(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoint => { endpoint.MapDefaultControllerRoute(); }); app.Run();
Previous Article also you can check ASP.Net Core Authentication and Authorization Basics in .Net Core 6.0
Create Controller
Create the Home Controller
using Auth_Identity_Login.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; namespace Auth_Identity_Login.Controllers { public class HomeController : Controller { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; public HomeController(UserManager<IdentityUser> userManager,SignInManager<IdentityUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } public IActionResult Index() { return View(); } public IActionResult Register() { return View(); } public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(UserViewModel model) { var user = await _userManager.FindByNameAsync(model.username); try { if (user != null) { var SignInResult = await _signInManager.PasswordSignInAsync(user, model.password,false,false); if (SignInResult.Succeeded) { TempData["Message"] = "Logged In"; return RedirectToAction(nameof(Index)); } } } catch (Exception) { TempData["Message"] = "User doesn't Exist"; return RedirectToAction(nameof(Index)); } TempData["Message"] = "Login Fail"; return RedirectToAction(nameof(Index)); } [HttpPost] public async Task<IActionResult> Register(UserViewModel model) { var userinfo = new IdentityUser { UserName = model.username, Email = string.Empty, }; var userresult = await _userManager.CreateAsync(userinfo,model.password); if (userresult.Succeeded) { var SignInResult = await _signInManager.PasswordSignInAsync(userinfo, model.password, false, false); if (SignInResult.Succeeded) { TempData["Message"] = "User Registered"; return RedirectToAction(nameof(Index)); } } TempData["Message"] = "User Registeration Fail"; return RedirectToAction(nameof(Index)); } public async Task<IActionResult> LogOut() { await _signInManager.SignOutAsync(); return RedirectToAction(nameof(Index)); } } }
Create View
Index.cshtml
@* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @{ } <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" /> <br/> <div class="container-fluid"> <div class="btn-group"> <a asp-controller="Home" asp-action="Register" class="btn-primary">Register</a> <br/> <a asp-controller="Home" asp-action="Login" class="btn-primary">Login</a> <h1>@TempData["Message"]</h1> </div> </div>
Login.cshtml
@* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @{ } <html> <head> <link rel="stylesheet" href="~/css/Style.css" /> </head> <body> <div class="login"> <h1>Login</h1> <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Login"> <p><input type="text" name="username" value="" placeholder="Username or Email" required></p> <p><input type="password" name="password" value="" placeholder="Password" required></p> <p class="remember_me"> <label> <input type="checkbox" name="remember_me" id="remember_me"> Remember me on this computer </label> </p> <p class="submit"><input type="submit" name="commit" value="Login"></p> <hr /> </form> </div> </body> </html>
Register.cshtml
@* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @{ } @model Auth_Identity_Login.Models.UserViewModel <html> <head> <link rel="stylesheet" href="~/css/Style.css" /> </head> <body> <div class="login"> <h1>User Registeration</h1> <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Register"> <p><input type="text" name="username" value="" placeholder="Username or Email" required></p> <p><input type="password" name="password" value="" placeholder="Password" required></p> <p class="remember_me"> <label> <input type="checkbox" name="remember_me" id="remember_me"> Remember me on this computer </label> </p> <p class="submit"><input type="submit" name="commit" value="Submit"></p> <hr /> </form> </div> </body> </html>