Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Comprehensive Guide to Monitoring and Observability

    April 21, 2025

    Comprehensive Guide to Cloud-Native Application Development

    April 21, 2025

    Comprehensive Guide to Kubernetes Container Orchestration

    April 21, 2025
    Facebook X (Twitter) Instagram
    Trending
    • Comprehensive Guide to Monitoring and Observability
    • Comprehensive Guide to Cloud-Native Application Development
    • Comprehensive Guide to Kubernetes Container Orchestration
    • Comprehensive Guide to Infrastructure as Code
    • Comprehensive Guide to CI/CD Pipelines
    • Go Backend Development: Gin and Echo Guide
    • Java Backend Development: Spring Boot Guide
    • Python Backend Development: Django and Flask Guide
    Facebook X (Twitter) Instagram
    Ijofed
    Subscribe
    Wednesday, June 11
    • Homepage
    • Frontend
    • Security
    • Devops
    • Backend
    Ijofed
    Home»Security»API Security: Protecting Your Web Services
    Security

    API Security: Protecting Your Web Services

    ijofedBy ijofedApril 21, 2025Updated:April 21, 2025No Comments3 Mins Read3 Views

    Learn how to secure your APIs with modern authentication, authorization, and protection mechanisms.

    1. JWT Authentication Implementation

    const jwt = require('jsonwebtoken');
    const express = require('express');
    const app = express();
    
    // Secret key (store in environment variable)
    const JWT_SECRET = process.env.JWT_SECRET;
    
    // Generate JWT token
    function generateToken(user) {
        return jwt.sign(
            {
                userId: user.id,
                role: user.role
            },
            JWT_SECRET,
            {
                expiresIn: '1h',
                algorithm: 'HS256'
            }
        );
    }
    
    // JWT middleware
    function authenticateToken(req, res, next) {
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
    
        if (!token) {
            return res.status(401).json({ error: 'No token provided' });
        }
    
        jwt.verify(token, JWT_SECRET, (err, user) => {
            if (err) {
                return res.status(403).json({ error: 'Invalid token' });
            }
            req.user = user;
            next();
        });
    }
    
    // Protected route
    app.get('/api/protected', authenticateToken, (req, res) => {
        res.json({ message: 'Access granted', user: req.user });
    });

    Example Request/Response

    # Request
    GET /api/protected
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    
    # Response
    {
        "message": "Access granted",
        "user": {
            "userId": "123",
            "role": "admin"
        }
    }

    2. Rate Limiting Implementation

    const rateLimit = require('express-rate-limit');
    const Redis = require('ioredis');
    const redis = new Redis();
    
    // Rate limiting middleware
    const apiLimiter = rateLimit({
        windowMs: 15 * 60 * 1000, // 15 minutes
        max: 100, // limit each IP to 100 requests per windowMs
        message: 'Too many requests from this IP, please try again later',
        handler: async (req, res) => {
            const ip = req.ip;
            const key = `rate_limit:${ip}`;
            
            // Track blocked requests
            await redis.incr(`blocked:${ip}`);
            await redis.expire(`blocked:${ip}`, 3600);
            
            res.status(429).json({
                error: 'Too many requests',
                retryAfter: res.getHeader('Retry-After')
            });
        }
    });
    
    // Apply to all routes
    app.use(apiLimiter);
    
    // Stricter limits for sensitive endpoints
    const sensitiveLimiter = rateLimit({
        windowMs: 60 * 60 * 1000, // 1 hour
        max: 5,
        message: 'Too many attempts, please try again later'
    });
    
    app.post('/api/reset-password', sensitiveLimiter, (req, res) => {
        // Password reset logic
    });

    3. Input Validation and Sanitization

    const { body, validationResult } = require('express-validator');
    const sanitizeHtml = require('sanitize-html');
    
    // Validation middleware
    const validateUserInput = [
        body('email').isEmail().normalizeEmail(),
        body('password')
            .isLength({ min: 8 })
            .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/),
        body('name')
            .trim()
            .isLength({ min: 2, max: 50 })
            .customSanitizer(value => sanitizeHtml(value)),
        (req, res, next) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(400).json({ errors: errors.array() });
            }
            next();
        }
    ];
    
    // Usage
    app.post('/api/users', validateUserInput, (req, res) => {
        // Process validated input
        const { email, password, name } = req.body;
        // Create user...
    });

    4. API Key Management

    const crypto = require('crypto');
    
    class ApiKeyManager {
        constructor() {
            this.keys = new Map();
        }
    
        generateKey(permissions) {
            const key = crypto.randomBytes(32).toString('hex');
            const hash = crypto.createHash('sha256').update(key).digest('hex');
            
            this.keys.set(hash, {
                permissions,
                createdAt: Date.now(),
                lastUsed: null
            });
            
            return key;
        }
    
        validateKey(key, requiredPermission) {
            const hash = crypto.createHash('sha256').update(key).digest('hex');
            const keyData = this.keys.get(hash);
            
            if (!keyData) return false;
            
            keyData.lastUsed = Date.now();
            return keyData.permissions.includes(requiredPermission);
        }
    
        revokeKey(key) {
            const hash = crypto.createHash('sha256').update(key).digest('hex');
            return this.keys.delete(hash);
        }
    }
    
    // Usage
    const apiKeyManager = new ApiKeyManager();
    const key = apiKeyManager.generateKey(['read', 'write']);
    
    // Middleware
    function validateApiKey(permission) {
        return (req, res, next) => {
            const apiKey = req.headers['x-api-key'];
            if (!apiKey || !apiKeyManager.validateKey(apiKey, permission)) {
                return res.status(401).json({ error: 'Invalid API key' });
            }
            next();
        };
    }

    ⚠️ Common API Security Mistakes

    1. Exposing sensitive data in error messages
    2. Not implementing rate limiting
    3. Weak or missing authentication
    4. Insufficient input validation
    5. Not using HTTPS

    ✅ API Security Best Practices

    1. Use JWT or OAuth 2.0 for authentication
    2. Implement proper rate limiting
    3. Validate and sanitize all input
    4. Use API keys for third-party access
    5. Enable CORS with proper configuration

    API Security Checklist

    1. ✅ Implement proper authentication
    2. ✅ Add rate limiting
    3. ✅ Validate all input
    4. ✅ Use HTTPS
    5. ✅ Implement proper error handling
    6. ✅ Enable CORS with restrictions
    7. ✅ Log security events
    8. ✅ Regular security audits

    Additional Resources

    • OWASP API Security Project
    • Auth0 Token Security Guide
    • OWASP REST Security Cheat Sheet
    Follow on Google News Follow on Flipboard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHTTPS & SSL/TLS: Securing Your Web Traffic
    Next Article Node.js Backend Development: A Comprehensive Guide
    ijofed
    • Website

    Related Posts

    HTTPS & SSL/TLS: Securing Your Web Traffic

    April 21, 2025

    Password Security: Protecting User Accounts

    April 21, 2025

    CSRF Protection: Stop Unauthorized Actions

    April 21, 2025
    Leave A Reply Cancel Reply

    Latest Posts

    Comprehensive Guide to Monitoring and Observability

    April 21, 20254 Views

    Comprehensive Guide to Cloud-Native Application Development

    April 21, 20252 Views

    Comprehensive Guide to Kubernetes Container Orchestration

    April 21, 20251 Views

    Comprehensive Guide to Infrastructure as Code

    April 21, 20251 Views
    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss

    Go Backend Development: Gin and Echo Guide

    By ijofedApril 21, 2025

    Introduction to Go Backend Development Go (Golang) has emerged as a powerful language for building…

    Comprehensive Guide to Monitoring and Observability

    April 21, 2025

    HTTPS & SSL/TLS: Securing Your Web Traffic

    April 21, 2025

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    © 2025 ThemeSphere. Designed by ThemeSphere.
    • About Us
    • Contact Us
    • Terms and Conditions
    • Disclaimer
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.