Skip to main content

Exercise 1: JWT Authentication Implementation

Objective

Implement JWT authentication with refresh tokens

Steps

1. Create Project

dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package BCrypt.Net-Next

2. Create Models

public record LoginRequest(string Email, string Password);
public record TokenResponse(string AccessToken, string RefreshToken);
public record User(int Id, string Email, string PasswordHash, string Role);

3. Implement TokenService

public class TokenService
{
// Generate access token (15 min expiry)
// Generate refresh token (7 days expiry)
// Validate refresh token
}

4. Create Endpoints

  • POST /api/auth/register
  • POST /api/auth/login
  • POST /api/auth/refresh
  • GET /api/auth/me (protected)

Expected Outcome

  • Working JWT authentication
  • Refresh token flow
  • Protected endpoints

Challenge

  • Add email verification
  • Implement token revocation/blacklist
  • Add role-based authorization