7. Authentication & Authorization

ASP.NET Core Authentication & Authorization - Complete Guide

Practical Guide + Technical Reference


📋 Table of Contents

Part 1: Practical Guide (Hands-On)

  1. Authentication vs Authorization Explained

  2. 3 Primary Authentication Methods (Cookie, JWT, Identity)

  3. Cookie Authentication Deep Dive

  4. JWT Authentication Deep Dive

  5. ASP.NET Core Identity Setup

  6. Authorization Patterns (Role, Claims, Policy)

  7. External Authentication Providers (OAuth/OpenID)

  8. Additional Authentication Methods (API Key, Certificate)

  9. Common Security Patterns

  10. Troubleshooting Common Issues

  11. Best Practices & Security Checklist

Part 2: Technical Reference (Deep Dive)

  1. Important Interfaces & Classes Reference

  2. Configuration Deep-Dive

  3. Advanced Topics

  4. Version Timeline


PART 1: PRACTICAL GUIDE


1. Authentication vs Authorization Explained

Simple Definitions

Authentication: "Who are you?"

  • Verifying user identity

  • Think: Showing your ID at airport security

Authorization: "What can you do?"

  • Checking permissions/access rights

  • Think: Having a boarding pass for first class

Visual Flow

Key Differences

Aspect
Authentication
Authorization

Purpose

Verify identity

Check permissions

When

Happens first

Happens after authentication

Result

Identity (ClaimsPrincipal)

Allow/Deny access

Example

Login with username/password

[Authorize(Roles = "Admin")]

Middleware

UseAuthentication()

UseAuthorization()


2. 3 Primary Authentication Methods

Quick Comparison

Method
Best For
Complexity
Stateless
Mobile-Friendly

Cookie

Traditional web apps

Simple

❌ No

❌ No

JWT

Modern APIs, SPAs

Medium

✅ Yes

✅ Yes

Identity

Full-featured apps

High

Depends

✅ Yes

When to Use Which?

Use Cookie Authentication when:

  • ✅ Building traditional MVC/Razor Pages app

  • ✅ Users log in through web browser

  • ✅ Session-based state is acceptable

  • ✅ Simple authentication needs

Use JWT Authentication when:

  • ✅ Building RESTful APIs

  • ✅ Need stateless authentication

  • ✅ Mobile app or SPA frontend

  • ✅ Microservices architecture

  • ✅ Cross-domain authentication

Use Identity Framework when:

  • ✅ Need full user management (register, login, roles, etc.)

  • ✅ Want built-in features (email confirmation, password reset, 2FA)

  • ✅ Enterprise applications

  • ✅ Don't want to build auth from scratch


When to use:

  • ✅ Server-rendered views (MVC/Razor Pages)

  • ✅ Browser-based authentication

  • ✅ Session management needed

  • ❌ Not ideal for APIs

  • ❌ Not mobile-friendly

Step-by-Step Setup

Step 1: Configure Cookie Authentication

Step 2: Create Login Action

Step 3: Create Logout Action

Step 4: Protect Actions

Complete Login View Example


4. JWT Authentication Deep Dive

Method 2: JWT (JSON Web Token) - Modern API Authentication

When to use:

  • ✅ RESTful APIs

  • ✅ Single Page Applications (SPAs)

  • ✅ Mobile applications

  • ✅ Microservices

  • ✅ Stateless authentication

  • ❌ Traditional web apps (use cookies instead)

What is JWT?

JWT Structure: header.payload.signature

Decoded:

Step-by-Step JWT Setup

Step 1: Install Required Package

Step 2: Add JWT Settings to appsettings.json

⚠️ NEVER commit the secret key to source control! Use User Secrets (development) or Azure Key Vault (production).

Step 3: Configure JWT Authentication

Step 4: Create JWT Token Service

Step 5: Create Login Endpoint (API)

Client-Side JWT Usage

JavaScript Example (Fetch API):

JWT Best Practices

  1. Use HTTPS - Always encrypt traffic

  2. Short expiration - 15-60 minutes recommended

  3. Implement refresh tokens - For long-lived sessions

  4. Validate all parameters - issuer, audience, expiry

  5. Use strong secret key - At least 256 bits

  6. Store tokens securely - HttpOnly cookies or secure storage

  7. Don't store sensitive data - Tokens are base64 encoded, not encrypted

  8. Don't trust token contents - Always validate signature


5. ASP.NET Core Identity Setup

When to use:

  • ✅ Need complete user management system

  • ✅ Want built-in features (register, login, roles, email confirmation, 2FA)

  • ✅ Enterprise applications

  • ✅ Don't want to implement auth from scratch

  • ❌ Overkill for simple authentication needs

Features included:

  • User registration & login

  • Password hashing & validation

  • Role management

  • Claims management

  • Email confirmation

  • Password reset

  • Two-factor authentication (2FA)

  • Account lockout

  • External login providers (Google, Facebook, etc.)

Step-by-Step Identity Setup

Step 1: Install Packages

Step 2: Create ApplicationUser (Custom User)

Step 3: Create ApplicationDbContext

Step 4: Configure Services in Program.cs

Step 5: Add Connection String to appsettings.json

Step 6: Create and Apply Migrations

This creates tables:

  • AspNetUsers

  • AspNetRoles

  • AspNetUserRoles

  • AspNetUserClaims

  • AspNetUserLogins

  • AspNetUserTokens

  • AspNetRoleClaims

Step 7: Create AccountController (Registration & Login)

Step 8: Seed Roles (Optional but Recommended)

Identity API Endpoints (For SPAs/Mobile)


6. Authorization Patterns (Role, Claims, Policy)

Pattern 1: Role-Based Authorization (Simple)

When to use:

  • ✅ Simple permission model

  • ✅ Users belong to predefined roles

  • ❌ Complex permission requirements

Pattern 2: Claims-Based Authorization (Flexible)

When to use:

  • ✅ Fine-grained permissions

  • ✅ User attributes beyond roles

  • ✅ Modern applications

What are Claims?

  • Key-value pairs describing the user

  • Examples: Name, Email, Age, Department, Permissions

When to use:

  • ✅ Complex authorization logic

  • ✅ Reusable authorization rules

  • ✅ Business logic in authorization

  • ✅ Modern best practice

Step 1: Create Authorization Requirement

Step 2: Create Authorization Handler

Step 3: Register Handlers and Policies

Step 4: Use Policies

Resource-Based Authorization

When to use:

  • ✅ Authorization depends on the resource being accessed

  • ✅ Example: Users can only edit their own posts


7. External Authentication Providers (OAuth/OpenID Connect)

Method 4: External Providers (Google, Facebook, Microsoft)

When to use:

  • ✅ Social login ("Sign in with Google")

  • ✅ Reduce password management burden

  • ✅ Improve user experience

  • ✅ Enterprise SSO (Single Sign-On)

Google Authentication Setup

Step 1: Get Google OAuth Credentials

  1. Create project

  2. Enable Google+ API

  3. Create OAuth 2.0 Client ID

  4. Add authorized redirect URI: https://localhost:5001/signin-google

  5. Copy Client ID and Client Secret

Step 2: Install Package

Step 3: Add to appsettings.json

⚠️ Use User Secrets for development:

Step 4: Configure Google Authentication

Step 5: Add External Login UI

Login View (Razor):

Multiple External Providers


8. Additional Authentication Methods

Method 5: API Key Authentication

When to use:

  • ✅ Machine-to-machine communication

  • ✅ Simple API access control

  • ✅ Third-party integrations

  • ❌ User-facing applications (use JWT instead)

Implementation:

Method 6: Certificate Authentication

When to use:

  • ✅ High-security requirements

  • ✅ Mutual TLS (mTLS)

  • ✅ Enterprise B2B scenarios

  • ❌ Public-facing applications


9. Common Security Patterns

Pattern 1: Refresh Tokens (For Long-Lived Sessions)

Why needed: JWT access tokens should be short-lived (15-60 min). Refresh tokens allow getting new access tokens without re-login.

Pattern 2: Password Reset with Tokens

Pattern 3: Email Confirmation

Pattern 4: Two-Factor Authentication (2FA)


10. Troubleshooting Common Issues

Issue 1: 401 Unauthorized Despite Valid Token

Problem:

Common Causes:

  1. Authentication middleware not added or in wrong order

  1. Token not sent correctly

  1. Token expired

  • Check token expiry time

  • Implement refresh token pattern

  1. Wrong authentication scheme

Issue 2: CORS Errors with Authentication

Problem:

Solution:

Issue 3: Claims Not Available After Login

Problem:

Solutions:

  1. Ensure claims are added during sign-in

  1. For Identity, add claims to user

  1. For JWT, include in token

Issue 4: Identity Scaffolding Issues

Problem: Can't scaffold Identity pages

Solution:

Issue 5: "Unable to resolve service" for UserManager

Problem:

Solution: Ensure Identity is registered before building app


11. Best Practices & Security Checklist

Authentication Best Practices

  • Always use HTTPS - Never send credentials over HTTP

  • Hash passwords - Use Identity or BCrypt, never plain text

  • Implement account lockout - Prevent brute force attacks

  • Use strong password requirements - Min 8 chars, upper, lower, digit, special

  • Implement 2FA - For sensitive applications

  • Short JWT expiry - 15-60 minutes recommended

  • Use refresh tokens - For long-lived sessions

  • Validate all token parameters - Issuer, audience, expiry, signature

  • Store secrets securely - User Secrets (dev), Key Vault (prod)

  • Implement rate limiting - Prevent abuse

  • Log authentication events - For security monitoring

  • Never log passwords - Even in error messages

  • Don't trust client data - Always validate server-side

  • Don't store tokens in localStorage - XSS vulnerable (use httpOnly cookies)

Authorization Best Practices

  • Principle of least privilege - Grant minimum necessary permissions

  • Use policy-based authorization - More flexible than role-based

  • Implement resource-based authorization - For user-owned resources

  • Check authorization at API level - Not just UI

  • Use [Authorize] by default - Opt-out with [AllowAnonymous]

  • Centralize authorization logic - Reusable policies and handlers

  • Test authorization - Unit test policies and handlers

  • Don't rely on client-side authorization - Always validate server-side

  • Don't expose sensitive data in errors - "Access denied" vs "User not found"

Security Checklist

Before Production:

Regular Security Maintenance:


PART 2: TECHNICAL REFERENCE


12. Important Interfaces & Classes Reference

ClaimsPrincipal Class ⭐⭐⭐

Purpose: Represents the authenticated user with all their identities and claims

Namespace: System.Security.Claims

Declaration:

Key Properties & Methods:

Member
Type
Description

Identity

Property

Primary identity (first in Identities)

Identities

Property

All identities for this principal

Claims

Property

All claims from all identities

FindFirst(type)

Method

Find first claim of type

FindAll(type)

Method

Find all claims of type

HasClaim(type, value)

Method

Check if claim exists

IsInRole(role)

Method

Check if user has role

Usage Examples:


ClaimsIdentity Class

Purpose: Represents a single identity with claims

Namespace: System.Security.Claims

Declaration:

Usage:


Claim Class

Purpose: Represents a single piece of information about the user

Declaration:

Common Claim Types:

ClaimTypes Constant
Value
Description

ClaimTypes.Name

name

Username

ClaimTypes.Email

email

Email address

ClaimTypes.NameIdentifier

sub

Unique user ID

ClaimTypes.Role

role

User role

ClaimTypes.DateOfBirth

birthdate

Date of birth

ClaimTypes.GivenName

given_name

First name

ClaimTypes.Surname

family_name

Last name

ClaimTypes.MobilePhone

phone_number

Phone number

JWT Registered Claims:

JwtRegisteredClaimNames
Description

Sub

Subject (user ID)

Name

Name

Email

Email

Jti

JWT ID (unique token ID)

Iat

Issued at

Exp

Expiration time

Nbf

Not before

Aud

Audience

Iss

Issuer

Usage:


UserManager Class ✨ Identity

Purpose: Manages users in the backing store

Namespace: Microsoft.AspNetCore.Identity

Key Methods:

Method
Description

CreateAsync(user, password)

Create user with password

UpdateAsync(user)

Update user

DeleteAsync(user)

Delete user

FindByIdAsync(userId)

Find user by ID

FindByNameAsync(username)

Find user by username

FindByEmailAsync(email)

Find user by email

CheckPasswordAsync(user, password)

Verify password

ChangePasswordAsync(user, oldPwd, newPwd)

Change password

AddToRoleAsync(user, role)

Add user to role

RemoveFromRoleAsync(user, role)

Remove user from role

GetRolesAsync(user)

Get user's roles

IsInRoleAsync(user, role)

Check if user in role

AddClaimAsync(user, claim)

Add claim to user

RemoveClaimAsync(user, claim)

Remove claim from user

GetClaimsAsync(user)

Get user's claims

GeneratePasswordResetTokenAsync(user)

Generate reset token

ResetPasswordAsync(user, token, newPwd)

Reset password with token

GenerateEmailConfirmationTokenAsync(user)

Generate email token

ConfirmEmailAsync(user, token)

Confirm email with token

SetTwoFactorEnabledAsync(user, enabled)

Enable/disable 2FA

GetTwoFactorEnabledAsync(user)

Check if 2FA enabled

Usage:


SignInManager Class ✨ Identity

Purpose: Manages user sign-in operations

Key Methods:

Method
Description

PasswordSignInAsync(username, password, isPersistent, lockout)

Sign in with password

SignInAsync(user, isPersistent)

Sign in user directly

SignOutAsync()

Sign out user

CheckPasswordSignInAsync(user, password, lockout)

Check password without signing in

ExternalLoginSignInAsync(loginProvider, providerKey, isPersistent)

Sign in with external provider

GetExternalLoginInfoAsync()

Get external login info

ConfigureExternalAuthenticationProperties(provider, redirectUrl)

Configure external auth

TwoFactorAuthenticatorSignInAsync(code, isPersistent, rememberClient)

Sign in with 2FA code

Usage:


RoleManager Class ✨ Identity

Purpose: Manages roles in the backing store

Key Methods:

Method
Description

CreateAsync(role)

Create role

UpdateAsync(role)

Update role

DeleteAsync(role)

Delete role

RoleExistsAsync(roleName)

Check if role exists

FindByNameAsync(roleName)

Find role by name

AddClaimAsync(role, claim)

Add claim to role

Usage:


IAuthorizationService Interface

Purpose: Evaluate authorization policies programmatically

Methods:

Usage:


AuthenticationProperties Class

Purpose: Stores state values related to authentication session

Key Properties:

Property
Description

IsPersistent

Whether authentication is persistent across sessions

ExpiresUtc

When authentication expires

IssuedUtc

When authentication was issued

AllowRefresh

Whether session can be refreshed

RedirectUri

Where to redirect after authentication

Usage:


13. Configuration Deep-Dive

Pattern 1: Inline Configuration (Quick)

When to use: Development, prototyping, simple scenarios

Pros: ✅ Quick, easy to understand Cons: ❌ Hardcoded values, not configurable, secrets in code


Pattern 2: Configuration Object (Better)

When to use: Production applications, need flexibility

Step 1: Create configuration class

Step 2: Add to appsettings.json

Step 3: Use in Program.cs

Pros: ✅ Configurable, environment-specific Cons: ❌ Still need to manually read configuration


When to use: Production applications, dependency injection, testability

Step 1: Create settings classes (same as Pattern 2)

Step 2: Register settings

Step 3: Inject and use in services

Pros: ✅ Dependency injection, testable, reusable, change monitoring Cons: ❌ Slightly more complex setup


IOptions vs IOptionsSnapshot vs IOptionsMonitor

Feature

IOptions

IOptionsSnapshot

IOptionsMonitor

Lifetime

Singleton

Scoped

Singleton

Reloads config

❌ No

✅ Yes (per request)

✅ Yes (immediately)

Use case

Static config

Per-request config

Real-time config changes

Performance

✅ Fastest

Good

Good

Named options

✅ Yes

✅ Yes

✅ Yes

When to use which:


Environment-Specific Configuration

appsettings.Development.json:

appsettings.Production.json:

Note: Don't put secrets in appsettings.Production.json! Use environment variables or Azure Key Vault.


Secret Management

Development - User Secrets:

Production - Environment Variables:

Production - Azure Key Vault:


14. Advanced Topics

Multiple Authentication Schemes

Scenario: Support both Cookie (for web) and JWT (for API) authentication


Custom Authentication Handler

When to use: Custom authentication logic not covered by existing schemes


Custom Authorization Requirement with Dependency Injection


Token Blacklisting (Revocation)

Problem: JWT tokens can't be revoked once issued

Solution: Maintain blacklist/revocation list


Sliding Expiration for JWT

Problem: Fixed JWT expiry means user gets logged out mid-session

Solution: Issue new token when current token is close to expiry


15. Version Timeline

ASP.NET Core Authentication & Authorization Evolution

Version
Year
New Features

Core 1.0

2016

• Basic Cookie & Bearer authentication • Role-based authorization • Claims-based authorization

Core 1.1

2016

• External authentication (Google, Facebook) • Policy-based authorization

Core 2.0

2017

• ASP.NET Core Identity • IMiddleware interface • Default authentication schemes • Resource-based authorization

Core 2.1

2018

• Identity UI (scaffolding) • GDPR features • Personal data protection APIs

Core 2.2

2018

• Health checks • Improved Identity scaffolding

Core 3.0

2019

• Endpoint routing integration • Authorization middleware improvements • Bearer token improvements

Core 3.1

2019

• Long-term support (LTS) • Performance improvements

.NET 5

2020

• Certificate authentication improvements • API versioning enhancements

.NET 6

2021

• Minimal APIs with authentication • JWT Bearer improvements • Microsoft.Identity.Web integration

.NET 7

2022

• Rate limiting (built-in) • Output caching • Auth improvements for minimal APIs

.NET 8

2023

• Identity API endpoints • Keyed DI services • Enhanced authentication options • Improved OpenAPI support

Key Milestones

✨ ASP.NET Core 2.0 - Identity framework introduced ✨ ASP.NET Core 3.0 - Endpoint routing (major architecture change) ✨ .NET 6 - Minimal APIs with authentication support ✨ .NET 8 - Identity API endpoints (no UI needed)


Summary & Quick Reference

Decision Tree: Which Authentication Method?

Common Patterns Quick Reference


END OF GUIDE 7: AUTHENTICATION & AUTHORIZATION


Page Count: ~40-45 pages (when printed) Last Updated: December 2024 ASP.NET Core Version: .NET 8.0 Status: ✅ Complete


Last updated