Part 7 — Add Login & Authentication (Identity) in ASP.NET Core MVC
ASP.NET Core Identity provides built-in features like:
We will integrate Identity into your Student Management project.
1. Install Identity Packages
If you created your project using "Empty" or "MVC" template without Identity, install these NuGet packages:
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
2. Add Identity DB Tables to Your DbContext
Open ApplicationDbContext.cs and change it to inherit from IdentityDbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
}
This automatically includes tables like:
AspNetUsers
AspNetRoles
AspNetUserRoles
AspNetUserClaims
AspNetRoleClaims
AspNetUserLogins
3. Register Identity in Program.cs
Open Program.cs and update:
using Microsoft.AspNetCore.Identity;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Identity
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/Login"; // redirect if not logged in
options.AccessDeniedPath = "/Account/AccessDenied";
});
var app = builder.Build();
app.UseAuthentication(); // MUST come before UseAuthorization
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();
4. Run Migration to Create Identity Tables
Execute:
Add-Migration AddIdentityTables
Update-Database
SQL Server will now contain all Identity tables.
5. Create Account Controller
Create Controllers/AccountController.cs:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
// Registration
[HttpGet]
public IActionResult Register() => View();
[HttpPost]
public async Task<IActionResult> Register(string email, string password)
{
var user = new IdentityUser { UserName = email, Email = email };
var result = await _userManager.CreateAsync(user, password);
if (result.Succeeded)
return RedirectToAction("Login");
foreach (var error in result.Errors)
ModelState.AddModelError("", error.Description);
return View();
}
// Login
[HttpGet]
public IActionResult Login() => View();
[HttpPost]
public async Task<IActionResult> Login(string email, string password)
{
var result = await _signInManager.PasswordSignInAsync(
email, password, false, false);
if (result.Succeeded)
return RedirectToAction("Index", "Home");
ModelState.AddModelError("", "Invalid login attempt");
return View();
}
// Logout
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Login");
}
public IActionResult AccessDenied() => View();
}
6. Create Login & Register Views
Views/Account/Login.cshtml
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
<form method="post">
<div class="form-group">
<label>Email</label>
<input name="email" class="form-control" />
</div>
<div class="form-group">
<label>Password</label>
<input name="password" type="password" class="form-control" />
</div>
<button class="btn btn-primary">Login</button>
</form>
Views/Account/Register.cshtml
<h2>Register</h2>
<form method="post">
<div class="form-group">
<label>Email</label>
<input name="email" class="form-control" />
</div>
<div class="form-group">
<label>Password</label>
<input name="password" type="password" class="form-control" />
</div>
<button class="btn btn-success">Register</button>
</form>
7. Protect Your Controllers or Actions
Add the [Authorize] attribute to protect Student pages.
Open StudentController.cs:
using Microsoft.AspNetCore.Authorization;
[Authorize]
public class StudentController : Controller
{
// only logged users can access
}
If not logged in → redirect to /Account/Login.
To allow anonymous access:
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
8. Login/Logout UI Links
In Views/Shared/_Layout.cshtml, add:
@if (User.Identity.IsAuthenticated)
{
<a href="/Account/Logout">Logout</a>
}
else
{
<a href="/Account/Login">Login</a>
<a href="/Account/Register">Register</a>
}
✔ Summary of Part 7
You successfully added:
Identity authentication
User registration & login
Cookie-based authentication
Authorization protection using [Authorize]
Login redirection rules
Automatic Identity tables using EF Core