Web Security Best Practices

Essential security practices every web developer should follow.

Input Validation

Always validate and sanitize user input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Bad - vulnerable to XSS
function displayUserInput(input) {
document.getElementById('output').innerHTML = input;
}

// Good - sanitize input
function displayUserInput(input) {
const sanitized = input
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;');
document.getElementById('output').textContent = sanitized;
}

SQL Injection Prevention

Use parameterized queries:

1
2
3
4
5
6
7
8
9
# Bad - vulnerable to SQL injection
def get_user(username):
query = f"SELECT * FROM users WHERE username = '{username}'"
return db.execute(query)

# Good - use parameterized queries
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

# Hashing a password
def hash_password(password):
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed

# Verifying a password
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
// Express.js example
const helmet = require('helmet');
app.use(helmet());

// Set custom headers
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
// Generate CSRF token
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) => {
// Process form
});

Security is not optional - make it a priority from day one!