1. Set Up User Authentication Foundation
Prepare your API for user authentication:
- Add a password field to your users table using
ALTER TABLE. - Install
bcryptandjsonwebtokenpackages with their TypeScript types. - Update your User interface and create a UserResponse interface.
- Set up JWT utilities and add JWT_SECRET to your environment variables.
2. Build Authentication Endpoints
Create user registration and login functionality:
- Create
routes/auth.tswith registration and login endpoints. - Implement secure password hashing using bcrypt in the registration endpoint.
- Use your Zod validation schemas from the previous lesson for input validation.
- Generate and return JWT tokens on successful login.
3. Protect Routes with JWT Authentication
Add authentication and authorisation to your existing routes:
- Create JWT authentication middleware to verify tokens.
- Add authentication middleware to protect routes and authorisation checks so users can only access/modify their own data.
- Test the complete authentication flow with valid/invalid tokens and different user access attempts.