Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Authentication vs Authorization in ASP.NET CORE

🔐 Authentication vs Authorization (Simple Example)

  • AuthenticationWho are you?

  • AuthorizationWhat are you allowed to do?

Example:

  • You login with username & password → ✅ Authentication

  • You access Admin Dashboard → ✅ Authorization


🔑 What is Authentication?

Authentication is the process of verifying user identity.

It checks:

  • Username

  • Password

  • Token

  • Cookies

  • OAuth 

Example

User logs in:

if(username == "admin" && password == "123")
{
   // user authenticated
}

Once authenticated:

  • User gets cookie

  • or JWT token

  • or session

Now user is logged in


🔐 What is Authorization?

Authorization decides what authenticated users can access.

Example:

  • Admin → Can delete users

  • Employee → Can view users

  • Guest → Can only view homepage


Example in ASP.NET Core MVC

Authentication Example

Enable authentication in Program.cs

builder.Services.AddAuthentication("CookieAuth")
    .AddCookie("CookieAuth", config =>
    {
        config.LoginPath = "/Account/Login";
    });

Authorization Example

Use [Authorize] attribute

[Authorize]
public IActionResult Dashboard()
{
    return View();
}

Only logged-in users can access this page.


Role-Based Authorization Example

[Authorize(Roles="Admin")]
public IActionResult AdminPanel()
{
    return View();
}

Only Admin users can access.


Authentication Flow in ASP.NET Core MVC

  1. User opens login page

  2. User enters username/password

  3. Server validates credentials

  4. Server creates cookie/token

  5. User becomes authenticated

  6. User accesses protected pages


Authorization Flow

  1. User logged in

  2. User tries to access Admin page

  3. System checks role

  4. If Admin → allow

  5. Else → deny access


Types of Authentication in ASP.NET Core

Common Types:

  • Cookie Authentication (Most common MVC)

  • JWT Authentication (API)

  • Identity Authentication (Recommended)

  • OAuth / Google / Microsoft Login


Most Recommended (ASP.NET Core MVC)

Use ASP.NET Core Identity 👍

Because it provides:

  • Login

  • Register

  • Roles

  • Password hashing

  • Security


Real World Example

Bank Website:

  • Login with username/password → Authentication

  • Access Account Details → Authorization

  • Transfer Money → Authorization (only logged-in users)


Interview Definition (Short)

Authentication:
Process of verifying the identity of a user.

Authorization:
Process of determining what an authenticated user is allowed to access.


🔐 ASP.NET Core Identity Setup (Step-by-Step) — ASP.NET Core MVC (.NET 9 / .NET 8)

ASP.NET Core Identity is built-in authentication system that provides:

✅ Login
✅ Register
✅ Logout
✅ Roles
✅ Password hashing
✅ User management


Step 1 — Create ASP.NET Core MVC Project

In Visual Studio:

File → New → Project → ASP.NET Core Web App (Model-View-Controller)

Select:

  • ✔ .NET 9.0 (or .NET 8)

  • ✔ Authentication Type → Individual Accounts (Recommended)

Click Create

👉 This automatically installs Identity


Step 2 — If Project Already Created (Manual Setup)

Install NuGet Packages:

Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.AspNetCore.Identity.UI
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Step 3 — Create ApplicationDbContext

Create folder Data

Create file ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

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

Step 4 — Configure Identity in Program.cs

Open Program.cs

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

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

app.Run();

Step 5 — Add Connection String

Open appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=IdentityDB;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

If using LocalDB:

Server=(localdb)\\mssqllocaldb;Database=IdentityDB;

Step 6 — Create Database (Migration)

Open Package Manager Console

Run:

Add-Migration InitialCreate

Then:

Update-Database

Now database created with tables:

  • AspNetUsers

  • AspNetRoles

  • AspNetUserRoles

  • AspNetUserClaims

  • AspNetUserLogins


Step 7 — Add Identity UI Pages

Run command:

Right Click Project → Add → New Scaffolded Item

Select:

Identity

Select:

  • Account/Login

  • Account/Register

  • Account/Logout

Click Add


Step 8 — Protect Controller with [Authorize]

Example:

using Microsoft.AspNetCore.Authorization;

[Authorize]
public class DashboardController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Now only logged-in users can access


Step 9 — Add Login/Register Links in Layout

Open:

Views/Shared/_Layout.cshtml

Add:

@if (User.Identity.IsAuthenticated)
{
    <a href="/Identity/Account/Logout">Logout</a>
}
else
{
    <a href="/Identity/Account/Login">Login</a>
    <a href="/Identity/Account/Register">Register</a>
}

Step 10 — Run Project

Now you have:

✅ Register page
✅ Login page
✅ Logout
✅ Database users
✅ Authentication system


Role Based Authorization (Optional Advanced)

Create Role:

await roleManager.CreateAsync(new IdentityRole("Admin"));

Authorize:

[Authorize(Roles="Admin")]
public IActionResult AdminPanel()
{
    return View();
}

Identity Architecture (Simple)

User → Login/Register
        ↓
ASP.NET Identity
        ↓
SQL Server Database
        ↓
Authentication Cookie
        ↓
Authorized Pages

Why Use ASP.NET Identity

✔ Secure
✔ Built-in
✔ Production Ready
✔ Password Hashing
✔ Role Management


Real World Example

  • Admin → Dashboard access

  • Student → Course access

  • Teacher → Upload content





Post a Comment

0 Comments