Secure Coding Practices
Write secure code with language-specific best practices that prevent common vulnerabilities. Covers input validation, output encoding, authentication, cryptography, and error handling patterns.
Usage
Specify your programming language and the security concern you want to address. The guide provides secure coding patterns with vulnerable vs. secure code comparisons and explanations of the underlying attack vectors.
Parameters
- Language: JavaScript/TypeScript, Python, Java, Go, PHP, Ruby, or C#
- Concern: Input validation, Authentication, Cryptography, Error handling, or General
- Framework: Express, Django, Spring, Next.js, Rails, or None
- Context: Web application, API, CLI tool, or Library
Examples
- SQL Injection Prevention: Language-specific parameterized query patterns for raw SQL, ORMs, and query builders — showing the vulnerable pattern and its secure replacement with explanation.
- XSS Prevention in React/Next.js: Safe rendering patterns, dangerouslySetInnerHTML alternatives, URL sanitization, and Content Security Policy implementation for modern React applications.
- Cryptography Done Right: Correct usage of bcrypt/argon2 for passwords, AES-GCM for encryption, HMAC for integrity, and crypto random for tokens — with common mistakes that break security.
- Secure File Upload: Complete secure file upload implementation — MIME type validation, filename sanitization, storage outside web root, size limits, and virus scanning integration.
Guidelines
- Every pattern shows vulnerable code alongside the secure version with diff highlights
- Attack scenarios explain HOW each vulnerability is exploited, not just that it's dangerous
- Input validation follows allowlist (whitelist) approach over denylist (blacklist)
- Output encoding is context-aware: HTML, JavaScript, URL, CSS, and SQL each need different encoding
- Cryptographic recommendations use current standards (no MD5, no SHA1 for security)
- Error messages don't leak internal details but provide useful feedback to legitimate users
- Session management covers creation, validation, expiration, and revocation
- Dependency management includes lockfiles, audit commands, and update strategies
- Security testing patterns (unit tests for auth, integration tests for access control) are provided
- Code review checklists focus on the security-critical sections of each pull request