Implementing JWT Authentication in Node.js
Explore how to secure your Node.js applications using JSON Web Tokens (JWT) for user authentication and authorization.
0 likes
49 views
Rule Content
{ "title": "Implementing JWT Authentication in Node.js", "description": "Explore how to secure your Node.js applications using JSON Web Tokens (JWT) for user authentication and authorization.", "category": "Node.js Cursor Rules", "rules": [ { "id": "jwt-strong-secret-keys", "description": "Use strong, complex secret keys for signing JWTs to prevent unauthorized token creation.", "recommendation": "Generate a secure, random secret key and store it in environment variables. Avoid hardcoding secrets in your codebase.", "example": "const crypto = require('crypto');\nconst secretKey = crypto.randomBytes(64).toString('hex');\nprocess.env.JWT_SECRET = secretKey;" }, { "id": "jwt-token-expiration", "description": "Set short expiration times for JWTs to minimize the risk of token misuse if compromised.", "recommendation": "Configure access tokens to expire within 15 to 60 minutes and implement refresh tokens for maintaining user sessions.", "example": "const jwt = require('jsonwebtoken');\nconst token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '15m' });" }, { "id": "jwt-https-transmission", "description": "Always transmit JWTs over HTTPS to protect against interception and man-in-the-middle attacks.", "recommendation": "Ensure your Node.js server enforces HTTPS connections, especially in production environments.", "example": "const express = require('express');\nconst app = express();\napp.use((req, res, next) => {\n if (!req.secure) {\n return res.redirect('https://' + req.headers.host + req.url);\n }\n next();\n});" }, { "id": "jwt-token-validation", "description": "Properly validate JWTs on the server to ensure their integrity and authenticity.", "recommendation": "Use a reliable library to verify the token's signature, expiration, and claims before processing requests.", "example": "const jwt = require('jsonwebtoken');\napp.use((req, res, next) => {\n const token = req.headers['authorization'].split(' ')[1];\n jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {\n if (err) return res.status(401).send('Unauthorized');\n req.user = decoded;\n next();\n });\n});" }, { "id": "jwt-sensitive-data", "description": "Avoid storing sensitive information in JWT payloads, as they can be decoded if intercepted.", "recommendation": "Only include non-sensitive data, such as user IDs or roles, in the JWT payload.", "example": "const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '15m' });" }, { "id": "jwt-refresh-tokens", "description": "Implement refresh tokens to maintain user sessions without requiring frequent logins.", "recommendation": "Use refresh tokens stored securely to issue new access tokens upon expiration.", "example": "const refreshToken = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '7d' });\n// Store refreshToken securely and use it to generate new access tokens as needed." }, { "id": "jwt-token-revocation", "description": "Implement a mechanism to revoke JWTs when necessary, such as during user logout or token compromise.", "recommendation": "Maintain a blacklist of revoked tokens and check against it during token validation.", "example": "const revokedTokens = new Set();\napp.post('/logout', (req, res) => {\n const token = req.headers['authorization'].split(' ')[1];\n revokedTokens.add(token);\n res.send('Logged out');\n});\napp.use((req, res, next) => {\n const token = req.headers['authorization'].split(' ')[1];\n if (revokedTokens.has(token)) return res.status(401).send('Unauthorized');\n next();\n});" }, { "id": "jwt-secure-storage", "description": "Store JWTs securely on the client side to prevent unauthorized access.", "recommendation": "Use HttpOnly cookies to store tokens, preventing access via JavaScript and mitigating XSS attacks.", "example": "res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });" } ] }