Skip to content
intermediatePhase 41 · Frontend Security

Frontend Security Questions

Practice common frontend security interview questions.

45m
0 problems
Topic Progress0%

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.

  1. Use bcrypt with salt rounds (12+)
  2. Never use MD5 or SHA for passwords
  3. Implement rate limiting
  4. Use account lockout
  5. 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

  1. Use OAuth 2.0 for third-party login
  2. Implement MFA for sensitive accounts
  3. Hash passwords with bcrypt
  4. Use secure session configuration
  5. Regenerate session IDs on login

Authorization

  1. Check permissions server-side
  2. Use principle of least privilege
  3. Validate user ownership
  4. Use role-based access control
  5. Audit access logs

Data Protection

  1. Encrypt sensitive data at rest
  2. Use HTTPS everywhere
  3. Sanitize user input
  4. Validate all data server-side
  5. Don't expose internal errors

Frontend Security

  1. Use React's auto-escaping
  2. Avoid dangerouslySetInnerHTML
  3. Set CSP headers
  4. Use secure cookies
  5. Store tokens securely

Testing

  1. Test for XSS vulnerabilities
  2. Test for CSRF protection
  3. Test authentication flows
  4. Test authorization checks
  5. 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

0/3solved
Build Security Interview Component

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 needed
Security Interview Testing

Write 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 tests
Security Interview Performance

Optimize 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 analysis

Quiz

1. What is the most common web security vulnerability?

Question 1 options

2. What is the principle of least privilege?

Question 2 options

3. What is the primary purpose of Security Interview?

Question 3 options

4. What is a common mistake when implementing Security Interview?

Question 4 options

Flashcards

Question

What are the top web security vulnerabilities?

Answer

XSS, CSRF, SQL Injection, Broken Authentication, Security Misconfiguration.

Question

What is security by obscurity?

Answer

Relying on secrecy for security instead of proper security measures.

Question

What is defense in depth?

Answer

Using multiple security layers so if one fails, others still protect.

Question

What is OWASP?

Answer

Open Web Application Security Project - provides security standards and tools.

Question

What is Security Interview?

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

  1. Broken Access Control
  2. Cryptographic Failures
  3. Injection
  4. Insecure Design
  5. Security Misconfiguration