Designing Secure, Reliable API Controllers: Signatures, Encryption, Rate Limiting & More
This article outlines best‑practice techniques for building robust API controller interfaces, covering request signing, RSA encryption, IP whitelisting, rate limiting, parameter validation, unified responses, exception handling, logging, idempotency, record limits, stress testing, asynchronous processing, data masking, and comprehensive documentation.
1. Signature
To prevent data tampering, the controller interface should be signed. The client concatenates request parameters, timestamp, and a secret key, then hashes (e.g., MD5) to generate a sign, which is sent as a parameter or header. The gateway recomputes the sign and compares; matching signs indicate a valid request, otherwise a signature error is returned. A timestamp limits the sign’s validity (e.g., 15 minutes) to prevent replay attacks. Two key management approaches are common: a shared static privateKey, or an AK/SK pair where the accessKey (AK) is sent in the header and the gateway retrieves the secret key (SK) to compute the sign.
2. Encryption
When the controller transmits sensitive data such as passwords, bank cards, or identity numbers, plaintext transmission is unsafe. Asymmetric encryption (e.g., RSA) is widely used: the public key resides in the front‑end to encrypt the data, while the private key stored securely on the back‑end decrypts it. This ensures that only the back‑end can read the original value.
3. IP Whitelist
Restrict API access to IP addresses placed on a whitelist. Requests from non‑whitelisted IPs are rejected with a “no access” error. The whitelist can be enforced at the gateway or via a web firewall such as ModSecurity.
4. Rate Limiting
Uncontrolled third‑party calls can overwhelm the service. Implement rate limiting at the gateway (e.g., Nginx, Redis, or a dedicated API gateway) by limiting total requests per IP, per specific endpoint, or per AK/SK user within a time window.
5. Parameter Validation
Validate required fields, data types, lengths, and enum values before business logic executes. Use validation frameworks (e.g., Hibernate Validator with @NotEmpty, @Size, @Max, @Min) or custom annotations for complex cases. Early validation prevents unnecessary database errors and protects against invalid data such as negative amounts or out‑of‑range enums.
6. Unified Response Format
Define a single JSON structure for all API responses, e.g., {"code":0,"message":null,"data":...}. Errors such as signature failure, permission denial, or internal exceptions should follow the same schema, allowing clients to parse responses consistently.
7. Unified Exception Handling
Capture all exceptions at the gateway, convert them to a standard error object (e.g., {"code":500,"message":"Internal Server Error","data":null}), and log detailed stack traces internally. This prevents leaking sensitive implementation details to third parties.
8. Request Logging
Record request URL, parameters, headers, method, response data, and latency. Include a traceId to correlate logs across services. Persist logs in a searchable store (e.g., MongoDB or Elasticsearch) and provide a UI for authorized third‑party users to view their own request logs.
9. Idempotency
Ensure that repeated rapid calls with identical parameters do not create duplicate records. Implement uniqueness constraints in the database or store request identifiers (e.g., requestId) in Redis to guarantee idempotent behavior.
10. Record Count Limitation
For batch endpoints, limit the number of records per request (commonly 500). Exceeding the limit should trigger a clear error message, and the limit should be configurable in agreement with partners.
11. Stress Testing
Before release, perform load testing (e.g., with JMeter or ApacheBench) to measure QPS and verify that rate‑limit thresholds are realistic. This helps size the required server fleet and avoid unexpected bottlenecks.
12. Asynchronous Processing
For long‑running or batch operations, return immediately after publishing a message to a queue. Consumers process the task asynchronously, and the client can obtain the result via a callback or periodic polling of a status endpoint.
13. Data Masking
Mask sensitive fields in responses (e.g., replace middle digits of a phone number with asterisks) to reduce exposure risk if data leaks.
14. Complete API Documentation
Provide a comprehensive spec that includes endpoint URL, HTTP method, request parameters, response fields, error codes, encryption/signature examples, a full request demo, and ancillary notes such as IP whitelist configuration. Use consistent naming conventions (e.g., camelCase) and version the API (e.g., v1/query/getCategory).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
