Implementing Secure Authentication Mechanisms in TypeScript
Delve into methods for creating robust and secure authentication systems within TypeScript applications.
0 likes
10 views
Rule Content
--- title: Implementing Secure Authentication Mechanisms in TypeScript description: Guidelines for creating robust and secure authentication systems within TypeScript applications. category: TypeScript Cursor Rules --- # Secure Authentication Mechanisms in TypeScript ## Context - Applicable to all TypeScript projects requiring user authentication. - Ensures the implementation of secure, scalable, and maintainable authentication systems. ## Requirements 1. **Password Hashing** - Use `bcrypt` to hash passwords before storing them in the database. - Example: ```typescript import bcrypt from 'bcrypt'; const hashedPassword = await bcrypt.hash(password, 10); ``` - Reference: [Secure Authentication with TypeScript and JWT](https://clouddevs.com/typescript/secure-authentication/) 2. **Token-Based Authentication** - Implement JSON Web Tokens (JWT) for user authentication. - Set token expiration to enhance security. - Example: ```typescript import jwt from 'jsonwebtoken'; const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' }); ``` - Reference: [Secure Authentication with TypeScript and JWT](https://clouddevs.com/typescript/secure-authentication/) 3. **Input Validation** - Validate all user inputs to prevent injection attacks. - Use libraries like `zod` for schema validation. - Example: ```typescript import { z } from 'zod'; const userSchema = z.object({ name: z.string().min(2), age: z.number().positive(), }); const validatedData = userSchema.parse(userInput); ``` - Reference: [Secure Coding in TypeScript: A Comprehensive Guide](https://sametyaman.com.tr/blog/secure-coding-in-typescript) 4. **Environment Variables for Sensitive Data** - Store sensitive information like database passwords and API keys in environment variables. - Use the `dotenv` package to manage environment variables. - Example: ```typescript import dotenv from 'dotenv'; dotenv.config(); const dbPassword = process.env.DB_PASSWORD; ``` - Reference: [Secure Coding in TypeScript: A Comprehensive Guide](https://sametyaman.com.tr/blog/secure-coding-in-typescript) 5. **Error Handling** - Implement proper error handling to avoid exposing sensitive information. - Use custom error classes and centralized error handlers. - Example: ```typescript class AppError extends Error { constructor(message: string, public statusCode: number) { super(message); } } function errorHandler(err: AppError) { console.error(err.message); } ``` - Reference: [Secure Coding in TypeScript: A Comprehensive Guide](https://sametyaman.com.tr/blog/secure-coding-in-typescript) 6. **Two-Factor Authentication (2FA)** - Implement 2FA to add an extra layer of security. - Use libraries like `speakeasy` for time-based one-time passwords (TOTP). - Example: ```typescript import speakeasy from 'speakeasy'; const secret = speakeasy.generateSecret({ length: 20 }); const token = speakeasy.totp({ secret: secret.base32, encoding: 'base32', }); ``` - Reference: [TypeScript and Authentication: Implementing a Secure Login Flow for Modern Web Applications](https://cloudactivelabs.com/connect/blog/typescript-and-authentication-implementing-a-secure-login-flow-for-modern-web-applications) 7. **Secure API Endpoints** - Ensure that only authenticated users can access protected API endpoints. - Implement middleware to verify JWTs. - Example: ```typescript import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; function authenticateToken(req: Request, res: Response, next: NextFunction) { const token = req.header('Authorization')?.split(' ')[1]; if (!token) return res.sendStatus(401); jwt.verify(token, SECRET_KEY, (err, user) => { if (err) return res.sendStatus(403); req.user = user; next(); }); } ``` - Reference: [TypeScript and Authentication: Implementing a Secure Login Flow for Modern Web Applications](https://cloudactivelabs.com/connect/blog/typescript-and-authentication-implementing-a-secure-login-flow-for-modern-web-applications) 8. **Sender-Constrained Tokens** - Implement sender-constrained tokens to bind tokens to the client that received them, preventing misuse if intercepted. - Utilize standards like Demonstrating Proof of Possession (DPoP). - Reference: [2025's Most Important API Security Trends](https://curity.io/blog/2025-top-api-security-trends/) ## Examples <example> **Good Practice: Implementing Password Hashing with bcrypt** import bcrypt from 'bcrypt'; async function registerUser(password: string) { const hashedPassword = await bcrypt.hash(password, 10); // Store hashedPassword in the database } </example> <example type="invalid"> **Bad Practice: Storing Plaintext Passwords** async function registerUser(password: string) { // Store password directly in the database } </example> <example> **Good Practice: Validating User Input with zod** import { z } from 'zod'; const userSchema = z.object({ username: z.string().min(3), email: z.string().email(), }); function validateUserInput(input: any) { return userSchema.parse(input); } </example> <example type="invalid"> **Bad Practice: Not Validating User Input** function processUserInput(input: any) { // Process input without validation } </example>