Add User Authentication to ASP.NET Core MVC 7 App

Mohamad MahmoodMohamad Mahmood
2 min read

Continue from https://hashnotes.hashnode.dev/adding-validation-to-aspnet-core-mvc-7-app-with-sqlite

In this tutorial, you’ll learn how to add user authentication to your ASP.NET Core MVC 7 app running in Replit , using Entity Framework Core and SQLite .

You'll:

  • Set up identity services

  • Create a login/register system

  • Protect pages with authorization

  • Use SQLite as the database backend

Prerequisites

Before starting this tutorial, you should already have:

  • A working ASP.NET Core MVC 7 app in Replit

  • Entity Framework Core and SQLite configured

  • EF migrations created and applied\A basic CRUD controller and views

Step 1: Install Required Identity Packages

Replit requires local tooling and specific versions of Identity packages. Run these commands:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 7.0.20

dotnet add package Microsoft.AspNetCore.Identity.UI --version 7.0.20

dotnet add package Microsoft.AspNetCore.Identity --version 7.0.20

Step 2: Update AppDbContext to Inherit from IdentityDbContext

Open Data/AppDbContext.cs:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MyMvcApp.Models;

namespace MyMvcApp.Data
{
    public class AppDbContext : IdentityDbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }

        public DbSet<BlogPost> BlogPosts { get; set; } = null!;
    }
}

Step 3: Register Identity Services in Program.cs

Update Program.cs to register Identity services and use cookies for authentication.

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MyMvcApp.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = "Data Source=blog.db";

// Register Entity Framework Core with SQLite
builder.Services.AddSqlite<AppDbContext>(connectionString);

// Register ASP.NET Core Identity with simplified password policy
builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredLength = 4;
})
.AddEntityFrameworkStores<AppDbContext>();

// Configure cookie-based authentication
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
});

// Add Controllers and Views
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// Enable Authentication and Authorization
app.UseAuthentication(); // Must be before UseAuthorization
app.UseAuthorization();

// Map default controller route
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

// Enable Razor Pages (needed for Identity UI)
app.MapRazorPages();

app.Run();

Step 4: Add Login View

Create _LoginPartial.cshtml:

@using Microsoft.AspNetCore.Identity

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

<ul class="navbar-nav ms-auto">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
    </li>
    <li class="nav-item">
        <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" method="post">
            <button type="submit" class="nav-link btn btn-link">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

Run Migrations

dotnet ef migrations add AddIdentityTables --project workspace.csproj
dotnet ef database update --project workspace.csproj

.

0
Subscribe to my newsletter

Read articles from Mohamad Mahmood directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohamad Mahmood
Mohamad Mahmood

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He studies at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).