Skip to main content

Authentication and Authorization Overview

Level: Beginner to Intermediate

ℹ️ Where This Fits

Authentication and authorization are security foundations. This overview prepares you for JWT, cookie authentication, ASP.NET Core Identity, roles, claims, and policies.

ℹ️ What You'll Learn
  • Authentication: Verify who you are (login, password correct?) → "You are John Teacher"
  • Authorization: Check what you're allowed to do (can you access this student record?) → "You can only see your class"
  • Identity: Who is the user? (user ID, username, email)
  • Roles: Group permissions (Admin, Teacher, Student roles grant different access levels)
  • Claims: User attributes (Role="Teacher", DepartmentId="1", CanCreateStudent=true)
  • Policies: Rules for authorization (policy "CanEditStudent" = (Role==Teacher AND OwnClass) OR Role==Admin)
  • JWT (JSON Web Token): Stateless auth token, client stores and sends with every request
  • Cookie authentication: Server stores session, cookie identifies session (stateful)
  • [Authorize]: Block access to action if user not authenticated (401 response if not logged in)
  • [Authorize(Roles = "Admin")]: Only Admin role can access (403 if not admin)
  • [Authorize(Policy = "TeacherOnly")]: Custom policy (more flexible than roles)
  • School Management roles: SuperAdmin (all access), Principal (school settings), Teacher (class students), Student (own data)
  • Password hashing: Never store plain password! Use bcrypt/PBKDF2 to hash (one-way)
  • Password validation: Hash user input + compare to stored hash (not decrypt, hashing is irreversible)
  • JWT workflow: User logs in → Server creates JWT → Client stores → Client sends JWT header → Server verifies
  • Common security mistakes: Storing plain passwords (catastrophic!), hardcoding credentials, exposing JWT token in logs

The Short Version

Authentication answers:

Who are you?

Authorization answers:

What are you allowed to do?

Example:

Login as teacher -> authentication
Allow teacher to mark attendance -> authorization

School App Example

UserAuthenticationAuthorization
StudentLogs in with credentialsCan view own marks
ParentLogs in with credentialsCan view own child's fee status
TeacherLogs in with credentialsCan mark attendance
AdminLogs in with credentialsCan manage users and reports

Authentication Flow

Typical login flow:

User enters username/password
App validates credentials
App creates authentication proof
Client sends proof with future requests
Server identifies the user

Authentication proof can be:

  • authentication cookie
  • JWT token
  • external provider token

Authorization Flow

After authentication:

User is known
App checks role/claim/policy
Request is allowed or denied

Example:

[Authorize(Roles = "Teacher")]
[HttpPost("attendance")]
public IActionResult MarkAttendance(MarkAttendanceRequest request)
{
return Ok();
}

Only authenticated users in the Teacher role can access this action.

Key Security Concepts

ConceptMeaning
IdentityInformation about who the user is
PrincipalCurrent authenticated user object
ClaimA fact about the user
RoleA named permission group
PolicyA rule that decides access
TokenProof sent by client to server

Claims

A claim is a fact about a user.

Examples:

Name = Anika
Email = anika@example.com
Role = Student
Class = 8
SchoolId = 42

In code:

var userName = User.Identity?.Name;
var roleClaims = User.Claims.Where(c => c.Type == ClaimTypes.Role);

Namespace:

using System.Security.Claims;

Roles

Roles group users by responsibility.

Admin
Teacher
Student
Parent
Accountant

Role authorization:

[Authorize(Roles = "Admin")]
public IActionResult GetAdminReports()
{
return Ok();
}

Multiple roles:

[Authorize(Roles = "Admin,Accountant")]
public IActionResult GetFeeReports()
{
return Ok();
}

Policies

Policies are more flexible than roles.

builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CanPublishResults", policy =>
{
policy.RequireRole("Admin", "ExamCoordinator");
});
});

Use policy:

[Authorize(Policy = "CanPublishResults")]
public IActionResult PublishResults()
{
return Ok();
}

Enable Authentication and Authorization

The exact authentication setup depends on cookie/JWT/Identity.

But middleware order is important:

💻 Try It — Console App
💡 Authentication must run before authorization.⌥ GitHub
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

Order:

Authenticate user first.
Then check what the user can access.
ApproachBest For
Cookie authenticationServer-rendered MVC/Razor apps
JWT bearer authenticationWeb APIs used by SPA/mobile apps
ASP.NET Core IdentityFull user management with passwords, roles, tokens
External loginGoogle, Microsoft, GitHub sign-in

For Web API plus React/Angular/mobile, JWT is common.

For MVC apps with Razor pages, cookies are common.

Password Safety

Never store plain text passwords.

Bad:

Password = "student123"

Real applications store password hashes using proven frameworks such as ASP.NET Core Identity.

Do not write your own password hashing system for production.

The Authorize Attribute

Require login:

[Authorize]
[HttpGet("profile")]
public IActionResult GetProfile()
{
return Ok();
}

Allow anonymous access:

[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
return Ok();
}

Namespace:

using Microsoft.AspNetCore.Authorization;

Common Mistakes

MistakeBetter Approach
Confusing authentication and authorizationLogin first, permission second
Storing plain passwordsUse secure password hashing/Identity
Putting role checks only in frontendEnforce authorization on backend
Forgetting UseAuthentication()Add it before UseAuthorization()
Returning sensitive data after login without checksUse [Authorize]
Creating your own token security casuallyUse proven libraries and defaults

Practice Task

Design security for a school API:

  1. Define roles: Admin, Teacher, Student, Parent.
  2. Mark attendance API as Teacher-only.
  3. Mark reports API as Admin-only.
  4. Allow login API anonymously.
  5. Write which parts would use authentication and authorization.

Quick Recap

QuestionAnswer
Authentication means?Who are you?
Authorization means?What can you do?
Role example?Teacher
Claim example?Email or SchoolId
Require login?[Authorize]
Allow public access?[AllowAnonymous]
🎯 Interview Favourite

Q: What is the difference between authentication and authorization?

Good Answer: "Authentication verifies who the user is, usually through login credentials, cookies, or tokens. Authorization checks what that authenticated user is allowed to do, using roles, claims, or policies. Authentication must happen before authorization. In ASP.NET Core, [Authorize] protects controllers or actions, roles can restrict access to groups such as Admin or Teacher, and policies can define more flexible access rules."

🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on ASP.NET Core Authentication and Authorization. Try these prompts:

  • "Explain authentication vs authorization using a school app."
  • "What are roles, claims, and policies?"
  • "When should I use JWT vs cookie authentication?"
  • "Show me examples of Authorize and AllowAnonymous attributes."

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

-> ASP.NET Core Version History (Reference)

nexcoding.in