Essential security practices every web developer should follow.
Always validate and sanitize user input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function displayUserInput(input) { document.getElementById('output').innerHTML = input; }
function displayUserInput(input) { const sanitized = input .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); document.getElementById('output').textContent = sanitized; }
|
SQL Injection Prevention
Use parameterized queries:
1 2 3 4 5 6 7 8 9
| def get_user(username): query = f"SELECT * FROM users WHERE username = '{username}'" return db.execute(query)
def get_user(username): query = "SELECT * FROM users WHERE username = ?" return db.execute(query, (username,))
|
Password Security
Hash passwords properly:
1 2 3 4 5 6 7 8 9 10 11
| import bcrypt
def hash_password(password): salt = bcrypt.gensalt() hashed = bcrypt.hashpw(password.encode('utf-8'), salt) return hashed
def verify_password(password, hashed): return bcrypt.checkpw(password.encode('utf-8'), hashed)
|
HTTPS and Secure Headers
Always use HTTPS and set security headers:
1 2 3 4 5 6 7 8 9 10 11
| const helmet = require('helmet'); app.use(helmet());
app.use((req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'DENY'); res.setHeader('X-XSS-Protection', '1; mode=block'); next(); });
|
CSRF Protection
Implement CSRF tokens:
1 2 3 4 5 6 7 8 9 10 11
| const csrf = require('csurf'); const csrfProtection = csrf({ cookie: true });
app.get('/form', csrfProtection, (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); });
app.post('/process', csrfProtection, (req, res) => { });
|
Security is not optional - make it a priority from day one!