Introduction

APIs are a common attack target. This guide covers best practices to secure RESTful APIs running on your Hostxpeed VPS.

1. Use API Keys or JWT

Require authentication for every request. Avoid sending keys in URLs; use Authorization header.

2. Enforce HTTPS Only

Redirect HTTP to HTTPS; use HSTS. Never accept plain HTTP for API calls.

3. Rate Limiting per API Key

Implement limits (e.g., 1000 req/hour) using Nginx limit_req or application middleware.

4. Input Validation and Sanitisation

Never trust client input. Validate types, length, range, and use parameterised queries.

5. JWT Security

Use short expiration, strong signing algorithm (RS256), and store secret outside code.

6. CORS Configuration

Restrict allowed origins, methods, headers. Never use Access-Control-Allow-Origin: * with credentials.

7. API Versioning

Include version in URL (e.g., /v1/resource) to manage changes and deprecation.

8. Log All API Requests

Log timestamp, API key (partial), endpoint, response status, IP address for audit.

9. Implement Request Signing (HMAC)

For high‑value APIs, require signed requests to prevent replay attacks.

10. API Gateway Pattern

Use KrakenD, Kong, or Nginx as a gateway to centralise security policies.

11. OAuth2 / OpenID Connect

For third‑party access, use OAuth2. Implement an authorisation server or delegate (Auth0, Keycloak).

12. Limit Payload Size

Set client_max_body_size in Nginx to avoid large request DoS.

13. Use API Keys with Short Lifespan

Rotate keys regularly; allow regeneration by users.

14. Disable Unnecessary HTTP Methods

Allow only GET, POST, PUT, DELETE, PATCH as needed. Block OPTIONS, TRACE.

15. Response Data Minimisation

Do not expose internal object details, stack traces, or database IDs in responses.

16. SQL Injection Prevention

Even with ORM, always use parameterised queries; validate all inputs.

17. DDoS Mitigation for APIs

As with web apps, use rate limiting and cloud scrubbing (Hostxpeed).

18. API Abuse Detection

Monitor for abnormal request patterns (e.g., high volume from one IP, scraping).

19. Security Headers for API JSON Responses

Add X-Content-Type-Options: nosniff and Cache-Control: no-store for sensitive data.

20. Regular Security Testing

Run API security scans (OAST, fuzzing) with tools like Postman or ZAP.

Conclusion

Authenticate, rate‑limit, validate input, and log all API calls. Use HTTPS and never expose more data than needed.