Expert guidance for building secure web applications following OWASP Top 10 best practices, implementing authentication/authorization, data protection, and comprehensive security measures from the start.
This skill has safety concerns that you should review before use. Some patterns were detected that may pose a risk.Safety score: 60/100.
KillerSkills scans all public content for safety. Use caution before installing or executing flagged content.
Expert guidance for building secure, robust web applications that protect user data and prevent common vulnerabilities.
This skill provides comprehensive security expertise covering OWASP Top 10 vulnerabilities, secure coding practices, authentication/authorization implementation, data protection, and modern threat prevention.
When writing code, always apply these fundamental principles:
1. **Security by Default**: Implement security measures from the start, not as an afterthought
2. **Least Privilege**: Grant minimum necessary permissions for all operations
3. **Defense in Depth**: Layer multiple security controls
4. **Input Validation**: Validate all inputs and sanitize all outputs
5. **Secure Error Handling**: Handle errors without leaking sensitive information
6. **Zero Trust**: Never trust, always verify
Implement proper role-based access control:
Protect data with strong encryption:
Prevent SQL injection, XSS, and command injection:
Build security into architecture:
Configure systems securely:
Maintain secure dependencies:
Implement robust authentication:
Ensure code and data integrity:
Monitor and detect security events:
Prevent unauthorized internal requests:
Use strong validation libraries:
```typescript
import { z } from 'zod';
import DOMPurify from 'dompurify';
// Schema-based validation
const userInputSchema = z.object({
email: z.string().email().max(254),
name: z.string().min(1).max(100).regex(/^[a-zA-Z\s]+$/),
message: z.string().min(1).max(1000),
});
// HTML sanitization
const sanitizeHtml = (dirty: string): string => {
return DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em'],
ALLOWED_ATTR: [],
});
};
// File upload validation
const validateFileUpload = (file: File): boolean => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
const maxSize = 5 * 1024 * 1024; // 5MB
if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type');
}
if (file.size > maxSize) {
throw new Error('File too large');
}
return true;
};
```
Escape output and implement CSP:
```typescript
// HTML escaping
const escapeHtml = (unsafe: string): string => {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
// CSP configuration
const CSP_POLICY = {
"default-src": "'self'",
"script-src": "'self' 'nonce-{NONCE}'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data: https:",
"connect-src": "'self' https://api.example.com",
"frame-src": "'none'",
"object-src": "'none'",
};
```
Implement token-based CSRF protection:
```typescript
// Token management
const useCSRFToken = () => {
const [csrfToken, setCSRFToken] = useState<string>('');
useEffect(() => {
fetch('/api/csrf-token', { credentials: 'include' })
.then(res => res.json())
.then(data => setCSRFToken(data.token));
}, []);
return csrfToken;
};
// Include in forms
<form method="POST">
<input type="hidden" name="_csrf" value={csrfToken} />
</form>
```
Secure token storage and validation:
```typescript
// Token manager with encryption
const TokenManager = {
setToken: (token: string) => {
const encrypted = CryptoJS.AES.encrypt(token, SECRET_KEY).toString();
localStorage.setItem('auth_token', encrypted);
},
getToken: (): string | null => {
try {
const encrypted = localStorage.getItem('auth_token');
if (!encrypted) return null;
const decrypted = CryptoJS.AES.decrypt(encrypted, SECRET_KEY);
return decrypted.toString(CryptoJS.enc.Utf8);
} catch {
return null;
}
},
};
// JWT validation
const validateJWT = (token: string): boolean => {
const decoded = jwtDecode(token);
return decoded.exp > Date.now() / 1000;
};
```
Implement granular permission systems:
```typescript
interface Permission {
resource: string;
action: string;
}
const hasPermission = (user: User, permission: Permission): boolean => {
const permString = `${permission.resource}:${permission.action}`;
return user.permissions.includes(permString) ||
user.roles.some(role => ROLE_PERMISSIONS[role]?.includes(permString));
};
// Protected component wrapper
const ProtectedComponent = ({ permission, children }) => {
const { user } = useAuth();
if (!user || !hasPermission(user, permission)) {
return <UnauthorizedAccess />;
}
return <>{children}</>;
};
```
Mask and encrypt sensitive data:
```typescript
// Sensitive data masking
const maskSensitiveData = {
email: (email: string) => {
const [username, domain] = email.split('@');
return `${username.slice(0, 2)}${'*'.repeat(username.length - 2)}@${domain}`;
},
phone: (phone: string) => phone.replace(/(\d{3})\d{3}(\d{4})/, '$1***$2'),
creditCard: (card: string) => card.replace(/\d(?=\d{4})/g, '*'),
};
// Client-side encryption for storage
const encryptSensitiveData = (data: any): string => {
return CryptoJS.AES.encrypt(JSON.stringify(data), KEY).toString();
};
```
Configure secure HTTP clients:
```typescript
// Axios with security interceptors
const secureApiClient = axios.create({
timeout: 10000,
withCredentials: true,
});
secureApiClient.interceptors.request.use((config) => {
config.headers['X-Requested-With'] = 'XMLHttpRequest';
config.headers['X-Frame-Options'] = 'DENY';
config.headers['X-Content-Type-Options'] = 'nosniff';
config.headers['X-Timestamp'] = Date.now().toString();
const token = TokenManager.getToken();
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
```
Implement comprehensive security headers:
```typescript
const SECURITY_HEADERS = {
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'nonce-{NONCE}'; object-src 'none'",
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
};
```
1. Validate email and password with Zod schema
2. Implement CSRF token in hidden field
3. Hash password client-side before transmission
4. Use secure API client with HTTPS
5. Store token securely after authentication
6. Implement rate limiting for login attempts
1. Validate all inputs with allow-list validation
2. Encrypt sensitive data before storage
3. Mask data in UI where appropriate
4. Use secure headers for all responses
5. Log access to sensitive resources
6. Implement proper access controls
1. Validate all request parameters
2. Implement authentication middleware
3. Check permissions for each endpoint
4. Sanitize response data
5. Add security headers
6. Rate limit requests
7. Log all security events
Before deploying, verify:
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/secure-web-application-development/raw