Security Best Practices
XSS prevention, content security policy, secure forms, and data protection.
Overview
Web security protects users and data from attacks.
Key Concepts
- XSS Prevention — Sanitize user input
- Content Security Policy — Restrict resource loading
- Secure Forms — CSRF protection
- HTTPS — Secure communication
- Input Validation — Client and server validation
Code Examples
<!-- Content Security Policy -->
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">
<!-- Secure form -->
<form action="/submit" method="POST">
<input type="hidden" name="_csrf" value="csrf-token-here">
<input type="text" name="username" required pattern="[a-zA-Z0-9]{3,20}">
<input type="email" name="email" required>
<button type="submit">Submit</button>
</form>
<script>
// XSS prevention
function sanitizeInput(input) {
const div = document.createElement('div');
div.textContent = input;
return div.innerHTML;
}
// Secure DOM manipulation
function safeSetHTML(element, content) {
element.textContent = content; // Safe - no HTML parsing
}
// For trusted HTML only
function setTrustedHTML(element, html) {
// Only use with trusted content
element.innerHTML = html;
}
// CSRF token generation
function generateCSRFToken() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
// Secure cookie settings
document.cookie = `session=${token}; Secure; HttpOnly; SameSite=Strict; Path=/`;
// Input validation
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
function validatePassword(password) {
// At least 8 chars, 1 uppercase, 1 lowercase, 1 number
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
return regex.test(password);
}
// Prevent clickjacking
if (window.top !== window.self) {
window.top.location = window.self.location;
}
</script>
Practice
Implement CSP headers and input sanitization for a form.