Common Security Questions
Common Security Questions
Q: What is XSS and how do you prevent it?
Cross-Site Scripting (XSS) injects malicious scripts into web pages.
Prevention:
- Use textContent instead of innerHTML
- Sanitize HTML with DOMPurify
- Use React's auto-escaping
- Set Content Security Policy headers
- Validate and sanitize user input
Q: What is CSRF and how do you prevent it?
Cross-Site Request Forgery tricks users into making unintended requests.
Prevention:
- Use SameSite cookies (strict or lax)
- Implement CSRF tokens
- Validate Origin/Referer headers
- Use custom headers for AJAX
- Only accept POST for state changes
Q: How do you store passwords securely?
Never store plain text passwords.
- Use bcrypt with salt rounds (12+)
- Never use MD5 or SHA for passwords
- Implement rate limiting
- Use account lockout
- Require strong passwords
Q: What is Content Security Policy?
CSP restricts which resources can be loaded and executed.
Content-Security-Policy: default-src 'self'; script-src 'self'
- Prevents XSS
- Controls resource loading
- Reports violations
- Use nonces for inline scripts
Security Hardening
Security Hardening
HTTP Security Headers
app.use((req, res, next) => {
// Prevent XSS
res.setHeader('X-XSS-Protection', '1; mode=block');
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// Prevent MIME sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');
// Content Security Policy
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self';"
);
// Referrer Policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// Permissions Policy
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
next();
});
HTTPS Everywhere
// Redirect HTTP to HTTPS
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https' && process.env.NODE_ENV === 'production') {
return res.redirect(`https://${req.header('host')}${req.url}`);
}
next();
});
// HSTS header
app.use((req, res, next) => {
res.setHeader(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains'
);
next();
});
Input Validation
// Server-side validation
const Joi = require('joi');
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).required(),
});
app.post('/login', (req, res) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details });
}
});
// Whitelist validation
function validateStatus(status) {
const allowed = ['active', 'inactive', 'pending'];
return allowed.includes(status);
}
Error Handling
// Don't expose internal errors
app.use((err, req, res, next) => {
console.error(err);
// Generic error message
res.status(500).json({ error: 'Internal server error' });
});
// Specific error messages
app.post('/login', (req, res) => {
const user = await authenticate(req.body);
if (!user) {
// Don't reveal which field was wrong
return res.status(401).json({ error: 'Invalid credentials' });
}
});
Rate Limiting
const rateLimit = require('express-rate-limit');
// General rate limiter
const generalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests
});
// Login rate limiter
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: 'Too many login attempts',
});
app.use('/api/', generalLimiter);
app.post('/login', loginLimiter);
Security Best Practices
Security Best Practices
Authentication
- Use OAuth 2.0 for third-party login
- Implement MFA for sensitive accounts
- Hash passwords with bcrypt
- Use secure session configuration
- Regenerate session IDs on login
Authorization
- Check permissions server-side
- Use principle of least privilege
- Validate user ownership
- Use role-based access control
- Audit access logs
Data Protection
- Encrypt sensitive data at rest
- Use HTTPS everywhere
- Sanitize user input
- Validate all data server-side
- Don't expose internal errors
Frontend Security
- Use React's auto-escaping
- Avoid dangerouslySetInnerHTML
- Set CSP headers
- Use secure cookies
- Store tokens securely
Testing
- Test for XSS vulnerabilities
- Test for CSRF protection
- Test authentication flows
- Test authorization checks
- Use security scanning tools
Common Mistakes
// Bad: Exposing errors
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
// Good: Generic errors
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
// Bad: Client-side only validation
function validateEmail(email) {
return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);
}
// Good: Server-side validation too
app.post('/register', (req, res) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details });
}
});
Security Checklist
## Authentication
- [ ] Passwords hashed with bcrypt
- [ ] Rate limiting on login
- [ ] Account lockout
- [ ] MFA for sensitive accounts
- [ ] Secure session configuration
## Authorization
- [ ] Server-side permission checks
- [ ] User ownership validation
- [ ] Role-based access control
## Data Protection
- [ ] HTTPS everywhere
- [ ] Input sanitization
- [ ] Output encoding
- [ ] Error handling
## Headers
- [ ] Content-Security-Policy
- [ ] X-Frame-Options
- [ ] X-Content-Type-Options
- [ ] X-XSS-Protection
Practice Problems
Create a reusable React component implementing Security Interview. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Security Interview using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Security Interview for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the most common web security vulnerability?
2. What is the principle of least privilege?
3. What is the primary purpose of Security Interview?
4. What is a common mistake when implementing Security Interview?
Flashcards
Question
What are the top web security vulnerabilities?
Click to reveal answer
Answer
XSS, CSRF, SQL Injection, Broken Authentication, Security Misconfiguration.
Question
What is security by obscurity?
Click to reveal answer
Answer
Relying on secrecy for security instead of proper security measures.
Question
What is defense in depth?
Click to reveal answer
Answer
Using multiple security layers so if one fails, others still protect.
Question
What is OWASP?
Click to reveal answer
Answer
Open Web Application Security Project - provides security standards and tools.
Question
What is Security Interview?
Click to reveal answer
Answer
Security Interview is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.XSS and CSRF are common web vulnerabilities
- 2.Use defense in depth with multiple security layers
- 3.Implement proper authentication and authorization
- 4.Set security headers for all responses
- 5.Test for security vulnerabilities regularly
Interview Tips
- •Explain common vulnerabilities and how to prevent them
- •Discuss security headers and their purposes
- •Know OWASP Top 10 and how to address each
Cheat Sheet
Security Interview Cheat Sheet
Common Vulnerabilities
- XSS: Inject scripts, prevent with sanitization
- CSRF: Forgery, prevent with tokens/SameSite
- SQL Injection: Prevent with parameterized queries
- Broken Auth: Use MFA, rate limiting
Security Headers
- CSP: Resource loading restrictions
- X-Frame-Options: Clickjacking prevention
- HSTS: Force HTTPS
- X-Content-Type-Options: MIME sniffing
Best Practices
- HTTPS everywhere
- Input validation (client + server)
- Output encoding
- Secure cookies (httpOnly, secure, sameSite)
- Password hashing (bcrypt)
- Rate limiting
- Error handling
OWASP Top 10
- Broken Access Control
- Cryptographic Failures
- Injection
- Insecure Design
- Security Misconfiguration