The authentication system of this project is designed with a strong emphasis on security, leveraging industry-standard practices to ensure both user privacy and the integrity of their sessions.
- JWT-based Authentication: At the core of the authentication system is the use of JSON Web Tokens (JWT). This stateless mechanism allows the server to securely verify user identities while maintaining scalability. Once logged in, users are issued a JWT that contains the necessary claims to validate their session without needing to store any session data on the server side.
- HttpOnly Cookies for Enhanced Security: To mitigate the risk of Cross-Site Scripting (XSS) attacks, the system uses HttpOnly cookies for storing the authentication token. These cookies are inaccessible to JavaScript running in the browser, making them less susceptible to malicious scripts attempting to steal sensitive information. This secure storage mechanism is complemented by the use of Secure and SameSite cookie attributes to enforce stricter security measures. With the Secure flag enabled, cookies are only sent over HTTPS connections, ensuring data is encrypted in transit. The SameSite attribute prevents cookies from being sent with cross-site requests, protecting the system from Cross-Site Request Forgery (CSRF) attacks.
- Refresh Tokens for Extended Sessions: To provide users with an optimal experience while maintaining security, the system implements a refresh token mechanism. This ensures that users stay logged in for extended periods without having to frequently reauthenticate. Once the access token expires, the system automatically issues a new one using the stored refresh token, reducing the likelihood of users being logged out unexpectedly.
- JWT Expiry and Token Revocation: JWTs have a built-in expiration time, ensuring that authentication tokens are automatically invalidated after a predefined period. Additionally, the system supports token revocation if needed, allowing administrators to invalidate any active tokens in case of suspicious activity or a security breach.
- User Login: When users provide valid credentials (username and password), the system authenticates them and issues an access token and refresh token. The access token is sent back to the client in an HttpOnly cookie, and the refresh token can be stored securely on the client or sent to the server for further processing.
- User Session: During the user's session, the access token is automatically included in the request headers for API calls to authenticate the user. The system checks the validity of the token before allowing any operations to be performed.
- Token Renewal: When the access token expires, the refresh token is used to request a new access token from the server. The server checks the validity of the refresh token and issues a new access token, extending the session without requiring the user to log in again.
- Protection Against XSS: Storing the JWT token in HttpOnly cookies ensures that it is not accessible by client-side JavaScript, making it less vulnerable to attacks like Cross-Site Scripting (XSS).
- Protection Against CSRF: By using the SameSite cookie attribute, the system mitigates the risk of Cross-Site Request Forgery (CSRF) attacks, which attempt to exploit a user's authenticated session.
- Efficient Token Handling: The use of JWTs allows for stateless authentication, reducing the risk of server-side session hijacking and improving system scalability. Furthermore, by using short-lived access tokens and refresh tokens for long-term session maintenance, the system ensures that tokens remain valid only for the necessary period.
With this secure and scalable authentication system, users can have peace of mind knowing that their data is protected while enjoying a seamless, long-lasting session experience.
This API allows users to interact with a blog platform by providing routes for authentication, user management, post management, and comments. The system uses JWT-based authentication with HttpOnly cookies to ensure high security against XSS and CSRF attacks.
File: authRoute.js
POST /api/register
- Register a new user.POST /api/login
- Authenticate a user and issue JWT tokens.POST /api/logout
- Log out the user by clearing cookies.POST /api/refreshtoken
- Refresh the access token using a refresh token.GET /api/auth/verify
- Verify the JWT token and provide user information if authenticated.
All authentication routes use JWTs stored in HttpOnly cookies for enhanced security. This prevents the tokens from being accessible to JavaScript, reducing the risk of token theft through XSS attacks.
File: userRoute.js
PUT /api/user/profile/:id
- Update a user’s profile information.GET /api/user/profile/:id
- Retrieve information for a specific user profile.GET /api/user/profile
- Get a list of all user profiles (Admin access only).POST /api/user/profile/upload-photo
- Upload a user’s profile photo.
Each user route is protected with role-based access control to restrict certain actions based on user roles. Admins have additional permissions to access or modify all user profiles, whereas regular users can only access and update their own profiles.
File: postRoute.js
GET /api/post/
- Retrieve a list of posts.GET /api/post/:id
- Retrieve details for a specific post.GET /api/post/count
- Get the total count of posts.DELETE /api/post/:id
- Delete a post.PUT /api/post/:id
- Update a post.PUT /api/post/like/:id
- Toggle like on a post.PUT /api/post/image/:id
- Update the image associated with a post.POST /api/post/
- Create a new post with an optional image.
All post-related routes are protected by JWT authentication. Only authenticated users can create, like, update, or delete posts. Each action is verified through token validation, ensuring that only authorized users can access or modify posts.
File: commentRoute.js
POST /api/comment/
- Create a new comment on a post.GET /api/comment/
- Retrieve all comments (Admin access only).
Comments are protected by JWT authentication. Only authenticated users can post comments, and only admins can retrieve all comments.
This API includes several middleware functions to enhance security, ensure data integrity, and manage error handling:
helmet
- Adds security headers to responses.cors
- Configured to allow requests from the specified frontend URL.express.json
- Parses incoming JSON payloads.xss
- Prevents XSS attacks by sanitizing input data.cookieParser
- Parses cookies from incoming requests.
The API has custom error-handling middleware to handle different errors effectively:
errorNotFoundHandler
- Returns a 404 error for any unknown route.errorHandler
- Manages all other server errors, sending appropriate HTTP status codes and messages.
To start the API, simply run the following command:
node index.js
The server will be running on localhost:4000.
Make sure to set up the required MongoDB connection string and JWT_SECRET in your .env
file.