Softechinfra
Technology

API Security Best Practices: OWASP Top 10 Protection Guide

Secure your APIs with authentication, authorization, input validation, and rate limiting. OWASP API Security Top 10 covered.

Softechinfra EditorialSoftechinfra Editorial
January 20, 202610 min read
API Security Best Practices: OWASP Top 10 Protection Guide

APIs power modern applications but are frequent targets for attackers. Our security-focused developers at Softechinfra share essential security practices for protecting your APIs.

91%
Companies Faced API Incident
$4.5M
Average Breach Cost
83%
Traffic is API Calls
10
OWASP Top Vulnerabilities

API Security Threats

⚠️ OWASP API Security Top 10

  1. Broken Object Level Authorization
  2. Broken Authentication
  3. Broken Object Property Level Authorization
  4. Unrestricted Resource Consumption
  5. Broken Function Level Authorization

Authentication

Best Practices

    Use Strong Authentication
  • OAuth 2.0 / OpenID Connect
  • JWT with proper validation
  • Short token lifetimes
  • Secure token storage

JWT Security

typescript
// Verify JWT properly
const verifyToken = (token: string) => {
  return jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'], // Specify algorithm
    issuer: 'your-app',
    audience: 'your-api',
    maxAge: '1h'
  });
};

API Keys

  • Use for identification, not authentication
  • Rotate regularly
  • Store securely
  • Rate limit per key
  • Authorization

    Object-Level Authorization

    typescript
    // Always check resource ownership
    app.get('/orders/:id', async (req, res) => {
      const order = await Order.findById(req.params.id);
    
      // Check ownership
      if (order.userId !== req.user.id) {
        return res.status(403).json({ error: 'Forbidden' });
      }
    
      return res.json(order);
    });

    Function-Level Authorization

    typescript
    // Role-based access control
    const requireAdmin = (req, res, next) => {
      if (!req.user.roles.includes('admin')) {
        return res.status(403).json({ error: 'Admin required' });
      }
      next();
    };
    
    app.delete('/users/:id', requireAdmin, deleteUser);

    Input Validation

    Validate Everything

    typescript
    import { z } from 'zod';
    
    const CreateUserSchema = z.object({
      email: z.string().email(),
      name: z.string().min(1).max(100),
      age: z.number().int().positive().max(150)
    });
    
    app.post('/users', (req, res) => {
      const result = CreateUserSchema.safeParse(req.body);
    
      if (!result.success) {
        return res.status(400).json({ errors: result.error.issues });
      }
    
      // Proceed with validated data
    });

    SQL Injection Prevention

    typescript
    // Use parameterized queries
    const user = await db.query(
      'SELECT * FROM users WHERE id = $1',
      [userId]
    );
    
    // Never string concatenation
    // WRONG: 'SELECT * FROM users WHERE id = ' + userId

    Rate Limiting

    Implementation

    typescript
    import rateLimit from 'express-rate-limit';
    
    const limiter = rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100, // 100 requests per window
      message: { error: 'Too many requests' }
    });
    
    app.use('/api/', limiter);

    Strategies

  • Per user/IP
  • Per endpoint
  • Different limits for auth/unauth
  • Consider business flows
  • Transport Security

    HTTPS Only

  • TLS 1.2+ required
  • HSTS headers
  • Certificate validation
  • No mixed content
  • Headers

    typescript
    app.use((req, res, next) => {
      res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
      res.setHeader('X-Content-Type-Options', 'nosniff');
      res.setHeader('X-Frame-Options', 'DENY');
      res.setHeader('Content-Security-Policy', "default-src 'self'");
      next();
    });

    Error Handling

    Secure Error Responses

    typescript
    // Don't expose internal details
    app.use((err, req, res, next) => {
      // Log full error internally
      logger.error(err);
    
      // Return generic message
      res.status(500).json({
        error: 'Internal server error',
        requestId: req.id
      });
    });

    Logging and Monitoring

    What to Log

  • Authentication attempts
  • Authorization failures
  • Input validation failures
  • Rate limit hits
  • Unusual patterns
  • Security Monitoring

  • Anomaly detection
  • Attack patterns
  • Real-time alerts
  • Regular audits
  • API Gateway

    Benefits

  • Centralized security
  • Rate limiting
  • Authentication
  • Logging
  • Protocol translation
  • Options

  • AWS API Gateway
  • Kong
  • Azure API Management
  • Apigee
  • Testing

    Security Testing

  • SAST (Static Analysis)
  • DAST (Dynamic Analysis)
  • Penetration testing
  • Dependency scanning
  • Automated Checks

  • OWASP ZAP
  • Burp Suite
  • SonarQube
  • Snyk
  • Conclusion

    "API security requires defense in depth. Implement authentication, authorization, validation, and monitoring. Test regularly and stay current with security practices."
    — Hrishikesh Baidya, Lead Developer

    Security is essential for all our API development. We implement secure APIs for projects like Radiant Finance using these best practices. See our zero-trust security guide and data privacy compliance guide for more.

    Need API Security Assessment?

    Our team provides security audits, penetration testing, and secure API development with proper authentication, authorization, and monitoring.

    Get Security Assessment
    Tags:
    API SecuritySecurityBackendAuthenticationBest Practices
    Share this post:
    Softechinfra Editorial

    Softechinfra Editorial

    Articles published by Softechinfra without a personal byline.

    How we pick topics, use AI, check claims and correct mistakes: our editorial policy.