Auth
The auth.controller.ts file handles user authentication using JWT tokens and refresh tokens. Authentication is handled via httpOnly cookies to improve security and prevent XSS attacks.
Key Functions
session
Verifies the user's current JWT session.
Flow:
- Retrieves the JWT token from the httpOnly cookie.
- Checks if the token exists. If not, returns an error.
- Verifies the token's validity and checks for expiration.
- If the token is expired, it triggers the
refreshfunction automatically.
refresh
Rotates the JWT and refresh token, issuing new tokens.
Flow:
- Retrieves the refresh token from a separate httpOnly cookie.
- Checks if the refresh token exists and whether it matches the token stored in the database for that user.
- If valid:
- Generates a new JWT token (expires every 15 minutes).
- Generates a new refresh token using
crypto.randomBytes(64).toString("hex")for security.
- Updates the database with the new refresh token string. This ensures that old refresh tokens cannot be reused, enhancing security.
- Reissues httpOnly cookies for both the new JWT and the new refresh token, refreshing their duration.
Explanation:
- The refresh token is a randomly generated string stored in the database.
- Whenever the JWT expires (every 15 minutes), the backend uses this refresh token to validate the user's session.
- If the refresh token matches the stored value, a new JWT and a new refresh token are created.
- The refresh token in the database is replaced with the new one, and both tokens are sent to the client in httpOnly cookies.
- This rotation ensures that a stolen or reused refresh token cannot be exploited.
Routes
The following routes are defined in auth.routes.ts and connect HTTP requests to the corresponding controller functions:
| Method | Path | Description | Controller Function |
|---|---|---|---|
| GET | /api/auth/session | Verifies the user's JWT session | session |
| GET | /api/auth/refresh | Rotates and issues new tokens | refresh |
Error Handling & Security Considerations
-
Missing Tokens: If the JWT or refresh token is missing, the controller responds with a
400 Bad Requestand an error message. -
Invalid Tokens: If the JWT or refresh token is invalid or expired, the controller responds with a
400 Bad Requestand an error message, preventing unauthorized access. -
Token Rotation: Refresh tokens are rotated on each successful refresh. Old tokens are replaced in the database, reducing the risk of replay attacks.
-
httpOnly Cookies: Both JWT and refresh tokens are stored in httpOnly cookies, making them inaccessible to client-side scripts and protecting against XSS attacks.
-
Secure Cookie Flags: In production, cookies are set with the
secureandsameSite="none"flags to ensure they are only sent over HTTPS and to mitigate CSRF risks. -
Error Responses: All errors are returned in a consistent JSON format, making it easier for clients to handle authentication failures.
Example Requests & Responses
Session Endpoint
Request:
GET /api/auth/session
Cookie: token=<JWT_TOKEN>
Successful Response:
{
"authenticated": true
}
Error Response (missing or invalid token):
{
"authenticated": false,
"error": "No token"
}
or
{
"authenticated": false,
"error": "Invalid token"
}
Refresh Endpoint
Request:
GET /api/auth/refresh
Cookie: refreshToken=<REFRESH_TOKEN>
Successful Response:
{
"success": true
}
Error Response (missing or invalid refresh token):
{
"error": "No refresh token"
}
or
{
"error": "Invalid refresh token"
}
Usage Instructions
- Sign In:
On successful login, the backend sets both
tokenandrefreshTokenas httpOnly cookies. - Session Validation:
Use the
api/auth/sessionendpoint to check if the user is authenticated. The backend verifies the JWT token. - Token Refresh:
If the JWT token expires, call
/api/auth/refreshwith therefreshTokencookie. The backend will issue new tokens and update the cookies. - Sign Out:
To log out, clear both
tokenandrefreshTokencookies on the client side.
Dependencies
- Express: Handles HTTP requests and responses.
- Jsonwebtoken: Used for creating and verifying JWT tokens.
- Crypto: Generates secure random refresh tokens.
- Prisma: ORM for PostgreSQL database operations.