How to Build Secure, Reliable API Controllers: Signatures, Encryption, Rate Limiting and More
This article explains how to design robust API controller interfaces by covering signature verification, RSA encryption, IP whitelisting, rate limiting, parameter validation, unified response formats, exception handling, request logging, idempotency, record limits, stress testing, asynchronous processing, data masking, and comprehensive documentation.
Introduction
When integrating with third‑party platforms, we often need to expose or consume controller APIs. Designing these APIs to be secure, repeatable, stable, and easy to troubleshoot is essential.
1. Signature
To prevent data tampering, the client concatenates request parameters, a timestamp, and a secret key, then generates a hash (e.g., MD5) to produce a sign. The sign is sent as a request parameter or header. The gateway recomputes the hash and compares the two signatures; a match indicates a valid request, otherwise a signature error is returned.
Including a timestamp limits the request’s validity period (e.g., 15 minutes) to mitigate replay attacks.
Two key management approaches are common: a shared static privateKey, or an AK/SK pair where the access key (AK) is sent in the header and the secret key (SK) is looked up server‑side.
2. Encryption
Sensitive data such as passwords, bank cards, or personal IDs must not be transmitted in plain text. Asymmetric encryption (RSA) is widely used: the public key resides in the front‑end code, while the private key is stored securely on the back‑end.
Clients encrypt the data with the public key; only the back‑end can decrypt it with the private key. Online tools can generate RSA key pairs.
3. IP Whitelist
To further protect the API, only IP addresses listed in a whitelist are allowed to access it. Requests from non‑whitelisted IPs receive an “access denied” response. The whitelist can be enforced at the gateway or web‑application firewall level.
4. Rate Limiting
Uncontrolled third‑party calls can overwhelm the service. Rate limiting can be applied per IP, per specific API, or per AK/SK user. Implementations often use nginx, redis, or a dedicated gateway.
5. Parameter Validation
Validate required fields, data types, lengths, and enumerations before processing. In Java, the Hibernate Validator framework (e.g., @NotEmpty, @Size) simplifies this, and custom annotations can handle complex cases.
6. Unified Response
Standardize the JSON response structure (e.g., {"code":0,"message":null,"data":{...}}). Errors such as signature failure, permission denial, or internal server errors should follow the same schema to simplify client handling.
{
"code":0,
"message":null,
"data":[{"id":123,"name":"abc"}]
} {
"code":1001,
"message":"Signature error",
"data":null
}7. Unified Exception Handling
Capture all runtime exceptions at the gateway, convert them to the standard error format (e.g., {"code":500,"message":"Internal server error","data":null}), and log detailed stack traces internally.
{
"code":500,
"message":"Internal server error",
"data":null
}8. Request Logging
Record request URL, parameters, headers, method, response data, and latency. Include a traceId to correlate logs across services. Logs can be persisted to databases such as MongoDB or Elasticsearch and exposed via a UI for third‑party users.
9. Idempotency Design
Ensure that repeated requests with the same parameters within a short window do not create duplicate records. Implement unique constraints in the database or store request IDs in Redis to enforce idempotency.
10. Record Limit
Batch APIs should limit the number of records per request (commonly 500). Exceeding the limit returns a clear error message, and the limit should be configurable.
11. Stress Testing
Before release, perform load testing (e.g., with JMeter or ApacheBench) to determine QPS limits and verify that rate‑limiting thresholds are realistic.
12. Asynchronous Processing
For long‑running or batch operations, push a message to a message queue and return success immediately. The consumer processes the task asynchronously, and the client can receive results via callbacks or polling.
13. Data Masking
Mask sensitive fields in responses (e.g., replace middle digits of a phone number with asterisks: 182****887) to protect user privacy.
14. Complete API Documentation
A thorough API spec should include endpoint URLs, HTTP methods, request/response fields, error codes, encryption/signature examples, sample requests, and notes such as IP whitelist requirements. Consistent naming (e.g., camelCase) and versioning (e.g., v1) improve maintainability.
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.
