331 lines
11 KiB
Markdown
331 lines
11 KiB
Markdown
# Feature: User Authentication & Authorization
|
|
|
|
> **Status**: 🚀 In Progress
|
|
> **Priority**: High
|
|
> **Complexity**: Medium
|
|
> **Estimate**: 4-6 hours
|
|
> **Assignee**: -
|
|
> **Created**: May 31, 2025
|
|
> **Target Completion**: -
|
|
> **PR**: -
|
|
> **Related Features**: Infrastructure Setup, Lesson Management
|
|
|
|
---
|
|
|
|
## 📌 Overview
|
|
|
|
### Purpose
|
|
Implement user authentication and authorization system using ASP.NET Core Identity with JWT token-based authentication.
|
|
|
|
### User Story
|
|
As a user, I want to register, login, and access my personalized learning content so that I can track my progress and continue from where I left off.
|
|
|
|
### Acceptance Criteria
|
|
- [ ] Users can register with username, email, and password
|
|
- [ ] Users can login with email and password
|
|
- [ ] Users receive JWT token upon successful authentication
|
|
- [ ] JWT token is required for protected API endpoints
|
|
- [ ] Token expiration and refresh mechanism
|
|
- [ ] Password hashing for security
|
|
- [ ] Current user information available via /api/auth/me
|
|
|
|
---
|
|
|
|
## 📋 Requirements
|
|
|
|
### Functional Requirements
|
|
| ID | Requirement | Priority |
|
|
|----|-------------|----------|
|
|
| FR-001 | User registration endpoint | High |
|
|
| FR-002 | User login endpoint | High |
|
|
| FR-003 | JWT token generation and validation | High |
|
|
| FR-004 | Protected routes require authentication | High |
|
|
| FR-005 | Current user endpoint | Medium |
|
|
| FR-006 | Password reset functionality | Low |
|
|
| FR-007 | Email verification (optional for MVP) | Low |
|
|
|
|
### Non-Functional Requirements
|
|
- Security: Passwords hashed with bcrypt or similar
|
|
- Security: JWT tokens expire after 24 hours
|
|
- Security: Refresh tokens for seamless UX
|
|
- Performance: Authentication < 500ms
|
|
- Compatibility: Works with React frontend
|
|
|
|
---
|
|
|
|
## 🏗️ Technical Design
|
|
|
|
### Components Involved
|
|
- **Backend**: AuthController, AuthService, JWT configuration
|
|
- **Database**: Users table (from initial schema)
|
|
- **Models**: User, LoginDto, RegisterDto, AuthResponse
|
|
- **Middleware**: JWT authentication middleware
|
|
|
|
### Data Flow
|
|
```
|
|
User Registration:
|
|
1. Frontend POST /api/auth/register with {username, email, password}
|
|
2. Backend validates input
|
|
3. Backend hashes password
|
|
4. Backend creates user in database
|
|
5. Backend generates JWT token
|
|
6. Returns {userId, token} to frontend
|
|
|
|
User Login:
|
|
1. Frontend POST /api/auth/login with {email, password}
|
|
2. Backend validates credentials
|
|
3. Backend generates JWT token
|
|
4. Returns {userId, token} to frontend
|
|
|
|
Protected Endpoint:
|
|
1. Frontend includes token in Authorization header
|
|
2. Backend middleware validates token
|
|
3. Backend processes request if valid
|
|
4. Returns 401 if token invalid/expired
|
|
```
|
|
|
|
### API Endpoints
|
|
| Endpoint | Method | Description | Auth Required |
|
|
|----------|--------|-------------|----------------|
|
|
| `/api/auth/register` | POST | Register new user | No |
|
|
| `/api/auth/login` | POST | Login existing user | No |
|
|
| `/api/auth/me` | GET | Get current user info | Yes |
|
|
| `/api/auth/logout` | POST | Invalidate token | Yes |
|
|
| `/api/auth/refresh` | POST | Refresh expired token | Yes |
|
|
|
|
### Database Schema (from application-plan.md)
|
|
```sql
|
|
CREATE TABLE Users (
|
|
Id SERIAL PRIMARY KEY,
|
|
Username VARCHAR(50) UNIQUE NOT NULL,
|
|
Email VARCHAR(100) UNIQUE NOT NULL,
|
|
PasswordHash VARCHAR(255) NOT NULL,
|
|
CurrentLevel VARCHAR(10) DEFAULT 'A1',
|
|
Streak INT DEFAULT 0,
|
|
TotalPoints INT DEFAULT 0,
|
|
CreatedAt TIMESTAMP DEFAULT NOW()
|
|
);
|
|
```
|
|
|
|
---
|
|
|
|
## 🚀 Implementation Plan
|
|
|
|
### Phase 1: Backend Authentication (3-4 hours)
|
|
- [x] Create User model and DTOs (RegisterDto, LoginDto, AuthResponse)
|
|
- [x] Configure ASP.NET Core Identity (using PasswordHasher with custom User)
|
|
- [x] Create AuthService with user registration logic
|
|
- [x] Create AuthService with user login logic
|
|
- [x] Configure JWT token generation
|
|
- [x] Create AuthController with endpoints
|
|
- [x] Add JWT authentication middleware
|
|
- [x] Configure CORS for frontend
|
|
- [x] Add [Authorize] to protected endpoints
|
|
|
|
### Phase 2: Database Integration (1-2 hours)
|
|
- [x] Update User entity to match schema
|
|
- [x] Configure EF Core user repository (via AppDbContext)
|
|
- [x] Implement password hashing (using PasswordHasher)
|
|
- [x] Create user seed data (admin user - in SeedDataExtension)
|
|
- [ ] Test database operations
|
|
|
|
### Phase 3: Token Management (1 hour)
|
|
- [x] Configure JWT settings in appsettings.json
|
|
- [x] Implement token validation middleware (via AddJwtBearer)
|
|
- [ ] Add token refresh mechanism
|
|
- [x] Set up token expiration (24 hours)
|
|
- [ ] Configure refresh token rotation
|
|
|
|
### Phase 4: Frontend Integration (Optional - if doing full stack)
|
|
- [ ] Create auth service in React
|
|
- [ ] Implement login/registration forms
|
|
- [ ] Store token in localStorage/cookies
|
|
- [ ] Add auth headers to API requests
|
|
- [ ] Handle token expiration
|
|
|
|
### Milestones
|
|
| Milestone | Date | Status |
|
|
|-----------|------|--------|
|
|
| Backend Auth Complete | 2025-06-05 | ✅ |
|
|
| Database Integration | 2025-06-05 | ✅ |
|
|
| Token Management | 2025-06-05 | ✅ |
|
|
| Frontend Integration | - | ⏳ |
|
|
|
|
---
|
|
|
|
## ✅ Tasks
|
|
|
|
### Backend
|
|
- [x] Create Models/User.cs with properties
|
|
- [x] Create DTOs/Auth/RegisterDto.cs
|
|
- [x] Create DTOs/Auth/LoginDto.cs
|
|
- [x] Create DTOs/Auth/AuthResponse.cs
|
|
- [x] Create Interfaces/IAuthService.cs
|
|
- [x] Create Services/AuthService.cs
|
|
- [x] Create Controllers/AuthController.cs
|
|
- [x] Configure JWT in Program.cs
|
|
- [x] Add [Authorize] attribute to protected endpoints (LessonsEndpoints)
|
|
- [ ] Create AuthMiddleware.cs
|
|
- [x] Configure CORS policy
|
|
- [ ] Write unit tests for AuthService
|
|
- [ ] Write integration tests for AuthController
|
|
|
|
### Database
|
|
- [x] Update User entity mapping (in AppDbContext)
|
|
- [ ] Create UserRepository (using DbContext directly for now)
|
|
- [x] Implement password hashing (PasswordHasher<User>)
|
|
- [x] Create migration for Users table (in InitialCreate migration)
|
|
- [x] Seed admin user (in SeedDataExtension)
|
|
|
|
### Token Management
|
|
- [x] Configure JWT settings (in appsettings.json)
|
|
- [x] Implement token generation (in AuthService)
|
|
- [x] Implement token validation (via AddJwtBearer)
|
|
- [ ] Implement token refresh
|
|
- [x] Set token expiration (24 hours)
|
|
|
|
### Frontend (Optional)
|
|
- [ ] Create authService.ts
|
|
- [ ] Create LoginPage component
|
|
- [ ] Create RegisterPage component
|
|
- [ ] Create AuthContext for user state
|
|
- [ ] Implement protected route wrapper
|
|
- [ ] Add logout functionality
|
|
|
|
---
|
|
|
|
## 🔗 Dependencies
|
|
|
|
### Feature Dependencies
|
|
- [Infrastructure Setup](infrastructure-setup.md) - Required (backend project and database)
|
|
|
|
### Technical Dependencies
|
|
- ASP.NET Core Identity
|
|
- JWT Bearer Authentication package
|
|
- BouncyCastle or similar for password hashing
|
|
|
|
### Blockers
|
|
- [ ] Infrastructure Setup must be complete first
|
|
|
|
---
|
|
|
|
## ✅ Definition of Done
|
|
|
|
### General Criteria (All Features)
|
|
- [ ] All acceptance criteria met and verified
|
|
- [ ] All tasks in this document completed
|
|
- [ ] Code follows Clean Architecture principles
|
|
- [ ] Code reviewed and approved by at least 1 team member
|
|
- [ ] All tests passing (unit, integration)
|
|
- [ ] Documentation updated (README, AGENTS.md if applicable)
|
|
- [ ] Feature works in development environment
|
|
- [ ] Feature deployed to staging environment
|
|
- [ ] Performance meets defined targets
|
|
- [ ] Security review completed
|
|
- [ ] No critical bugs or blockers
|
|
|
|
### Authentication-Specific Criteria
|
|
- [ ] Users can successfully register with valid credentials
|
|
- [ ] Users can successfully login with valid credentials
|
|
- [ ] Invalid credentials are rejected with appropriate error messages
|
|
- [ ] JWT tokens are generated and validated correctly
|
|
- [ ] Token expiration works as configured
|
|
- [ ] Token refresh mechanism works
|
|
- [ ] Protected endpoints reject requests without valid tokens
|
|
- [ ] Passwords are hashed and never stored in plain text
|
|
- [ ] Rate limiting on auth endpoints configured
|
|
|
|
---
|
|
|
|
## 🧪 Testing Strategy
|
|
|
|
### Testing Approach
|
|
|
|
| Test Type | Coverage | Tools | Responsibility |
|
|
|-----------|----------|-------|----------------|
|
|
| Unit Tests | 80%+ code coverage | MsTest, Moq | Backend Dev |
|
|
| Integration Tests | All service interactions | MsTest, TestContainers | Backend Dev |
|
|
| API Tests | All endpoints | MsTest, HttpClient | Backend Dev |
|
|
| Frontend Unit Tests | Component logic | Vitest | Frontend Dev |
|
|
| Frontend Integration | Service integration | Vitest | Frontend Dev |
|
|
| E2E Tests | Critical user journeys | Playwright | QA/Dev |
|
|
| Manual Testing | Exploratory, edge cases | BrowserStack | QA |
|
|
|
|
### Authentication-Specific Tests
|
|
|
|
#### Backend Tests
|
|
- [ ] Register with valid data → success
|
|
- [ ] Register with duplicate email → error
|
|
- [ ] Register with duplicate username → error
|
|
- [ ] Register with invalid password → error
|
|
- [ ] Login with valid credentials → success
|
|
- [ ] Login with invalid email → error
|
|
- [ ] Login with invalid password → error
|
|
- [ ] Login with valid token → success
|
|
- [ ] Login with expired token → error
|
|
- [ ] Login with invalid token → error
|
|
- [ ] Access protected endpoint without token → 401
|
|
- [ ] Access protected endpoint with valid token → success
|
|
- [ ] Access protected endpoint with invalid token → 401
|
|
- [ ] Token refresh → new valid token
|
|
- [ ] Rate limiting on login attempts → 429 after N attempts
|
|
|
|
#### Frontend Tests
|
|
- [ ] Registration form validation
|
|
- [ ] Registration form submission
|
|
- [ ] Login form validation
|
|
- [ ] Login form submission
|
|
- [ ] Token storage in localStorage/cookies
|
|
- [ ] Token inclusion in API requests
|
|
- [ ] Protected route redirection
|
|
- [ ] Logout functionality
|
|
- [ ] Session expiration handling
|
|
|
|
---
|
|
|
|
## 📝 Notes & Decisions
|
|
|
|
### Decisions Made
|
|
| Date | Decision | Rationale |
|
|
|------|----------|-----------|
|
|
| May 31, 2025 | Use JWT over cookies | Stateless, works well with SPAs, scalable |
|
|
| May 31, 2025 | ASP.NET Core Identity | Built-in, well-tested, integrates with EF Core |
|
|
| May 31, 2025 | 24-hour token expiration | Balance between security and UX |
|
|
|
|
### Technical Notes
|
|
- Store only password hash, never plain text
|
|
- Use HttpOnly cookies for refresh tokens if possible
|
|
- Sanitize username/email inputs to prevent injection
|
|
- Rate limit login attempts to prevent brute force
|
|
|
|
### Gotchas
|
|
- ⚠️ JWT secret must be long and random (>32 characters)
|
|
- ⚠️ Token must be stored securely on frontend (HttpOnly cookie or secure localStorage)
|
|
- ⚠️ CORS must be configured to accept credentials if using cookies
|
|
- ⚠️ Password hashing should use work factor appropriate for your hardware
|
|
|
|
---
|
|
|
|
## 📊 Progress History
|
|
|
|
| Date | Status Change | Notes |
|
|
|------|---------------|-------|
|
|
| May 31, 2025 | Created | Initial plan based on application-plan.md |
|
|
| Jun 05, 2025 | Status: Planned → In Progress | Started implementation |
|
|
| Jun 05, 2025 | Backend Auth Complete | DTOs, AuthService, AuthController, JWT configured |
|
|
| Jun 05, 2025 | Database Integration Complete | User entity, password hashing, seed data |
|
|
| Jun 05, 2025 | Token Management Complete | JWT settings, token generation/validation |
|
|
|
|
---
|
|
|
|
## 📎 Related Files & Links
|
|
|
|
- Architecture: [Backend Structure](../architecture/backend-structure.md)
|
|
- Database Schema: [Initial Database Schema](../database/initial-database-schema.sql)
|
|
- Application Plan: [Application Plan](../architecture/application-plan.md)
|
|
- Reference: [ASP.NET Core Identity Docs](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity)
|
|
- Reference: [JWT in .NET](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/jwt/)
|
|
|
|
---
|
|
|
|
*Feature created from application-plan.md*
|