Web Security Essentials: Protecting Your Applications

Web security is not optional. Every application faces threats from attackers. This guide covers the most critical vulnerabilities and how to prevent them.

## OWASP Top 10

The most common web application security risks.

## 1. Injection Attacks

```javascript
// Bad: SQL injection
const query = `SELECT * FROM users WHERE name = '${userInput}'`;

// Good: Parameterized queries
const query = 'SELECT * FROM users WHERE name = ?';
db.query(query, [userInput]);

// Bad: XSS
innerHTML = userInput;

// Good: Escape output
textContent = userInput;
```

## 2. Authentication

```javascript
// Never store plain-text passwords
// Always hash with bcrypt
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);
const match = await bcrypt.compare(input, hash);
```

## 3. CSRF Protection

- Use anti-CSRF tokens
- Set SameSite cookie attribute
- Verify origin header

## 4. Security Headers

```
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000
X-XSS-Protection: 1; mode=block
```

## 5. Input Validation

```javascript
const Joi = require('joi');
const schema = Joi.object({
 email: Joi.string().email().required(),
 age: Joi.number().min(0).max(150)
});
const { error } = schema.validate(data);
```

## 6. Rate Limiting

```javascript
const rateLimit = require('express-rate-limit');
app.use(rateLimit({
 windowMs: 15 * 60 * 1000,
 max: 100
}));
```

## 7. HTTPS Everywhere

- Use TLS for all traffic
- Redirect HTTP to HTTPS
- Use HSTS headers

## Conclusion

Security is a continuous process. Audit regularly, keep dependencies updated, and follow the principle of least privilege.

评论
暂无评论