Overview
The E-commerce API uses JWT (JSON Web Tokens) for authentication. After successful login, you receive a token that must be included in subsequent requests to protected endpoints.Authentication Flow
- Register a new user or login with existing credentials
- Receive a JWT token in the response
- Include the token in the
Authorizationheader for protected requests - Token expires after the configured duration (default: 1 hour)
Authentication Endpoints
Register New User
Create a new customer account.name: Required stringemail: Valid email formatpassword: Minimum 6 characters
Login
Authenticate and receive a JWT token.Create User with Role (Admin Only)
Administrators can create users with specific roles.customeradmin
Update Profile
Update authenticated user’s profile information.Delete Account
Delete the authenticated user’s account.Using JWT Tokens
Token Structure
JWT tokens contain the following payload:/workspace/source/backend/src/utils/jwt.ts:8-12
Including Tokens in Requests
Add the token to theAuthorization header using the Bearer scheme:
Token Expiration
Tokens expire after a configured duration (default: 1 hour). The expiration time is controlled by theJWT_EXPIRY environment variable.
When a token expires, you’ll receive a 401 Unauthorized response:
Authentication Middleware
The authentication middleware validates tokens and extracts user information:Security Best Practices
Token Storage
- Never store tokens in localStorage (vulnerable to XSS)
- Use httpOnly cookies for web applications
- Store in secure storage on mobile apps
Token Transmission
- Always use HTTPS in production
- Never send tokens in URL parameters
- Use the Authorization header
Token Security
- Keep
JWT_SECRETenvironment variable secure and complex - Rotate secrets periodically
- Use appropriate expiration times (shorter is more secure)
Common Authentication Errors
| Status | Error | Cause |
|---|---|---|
| 401 | ”Unauthorized” | No token provided |
| 401 | ”Invalid token” | Token is malformed, expired, or invalid |
| 403 | ”Forbidden” | Valid token but insufficient permissions |
| 409 | ”Resource already exists” | Email already registered |
| 422 | Validation error | Invalid input data format |