11 Essential Practices to Secure Your APIs – From Validation to Risk Control
This article outlines eleven practical techniques for protecting API endpoints, covering parameter validation, unified response wrapping, XSS escaping, captcha integration, rate limiting, IP whitelisting, sensitive‑word checks, HTTPS adoption, data encryption, and comprehensive risk control measures, each illustrated with concrete code snippets and step‑by‑step workflows.
1. Parameter Validation
Validate incoming request parameters to block malformed or malicious calls. The author recommends four checks: Check for null – ensure required fields are present. Check type – reject values like a string "123abc" for an int field age. Check length – enforce limits such as a username column of length 30; if the input exceeds 30 characters, return an error. Check enum values – for fields like status that only accept 1, 2, or 3, reject any other value. Check numeric range – e.g., a transaction amount money must be >0 and <10,000.
These checks can be coded manually or delegated to validation frameworks such as Hibernate Validator, which provides annotations like @NotEmpty, @Size, @Max, and @Min. Custom annotations may be needed for date or enum fields.
2. Unified Response Wrapping
Instead of returning raw SQL errors that expose database schema, wrap all responses in a standard JSON structure:
{
"code":0,
"message":null,
"data":[{"id":123,"name":"abc"}]
}The code field distinguishes success (0) from errors (1‑5), message holds a user‑friendly description, and data carries the payload. This wrapper should be applied at the API‑gateway level so that internal exceptions are transformed into the generic "Server internal error" message.
3. XSS Escaping
When user‑generated content is rendered as HTML (e.g., article or contract pages), escape dangerous tags. The author shows an example of a malicious payload <script>alert("XSS")</script> and provides a table of characters to escape. A custom annotation combined with an AOP interceptor can perform the escaping before persisting data.
4. Access Control
Three layers of permission checks are described:
4.1 Login Verification
Public data (e.g., external categories) requires no login, while internal data demands a non‑null user context; otherwise the request is rejected.
4.2 Functional Permission
Critical endpoints (e.g., order‑approval) need a custom permission annotation. An interceptor at the gateway matches the user's permission set against the required permission point before allowing execution.
4.3 Data‑level Permission
Different roles see different data ranges. The author suggests dynamically appending SQL filters based on the user's role (e.g., ordinary operators see only their own customers, managers see all).
5. Captcha Integration
To deter automated abuse, the article recommends adding captchas to high‑risk endpoints. Simple image captchas can be strengthened with noise, while sliding‑puzzle captchas provide higher security. For SMS‑sending APIs, a captcha alone is insufficient; a combination of captcha and rate limiting is needed.
6. Rate Limiting
The author outlines a Redis‑backed flow:
Query the most recent SMS record for the phone number.
If none exists, send the SMS.
If a record exists and the last send time is >60 seconds ago, send a new SMS.
If the interval is <60 seconds, return a "too frequent" error.
To prevent daily abuse, a per‑day counter (e.g., max 10 messages per number) is stored with a 24‑hour TTL. Exceeding the limit also returns a throttling error.
7. IP Whitelisting
Critical services (e.g., membership activation) should only accept calls from IPs listed in a whitelist, which can be managed via Apollo configuration or a database. Internal services using Feign with private DNS bypass the need for a whitelist.
8. Sensitive‑Word Filtering
For user‑generated text (e.g., product names), the article advises a two‑step approach: download an open‑source word list from GitHub, load it into a database, and use HanLP for tokenization. A custom annotation triggers an AOP interceptor that calls the filter service; a whitelist handles false positives.
9. HTTPS Adoption
HTTP transmits data in clear text, lacks authentication, and cannot guarantee integrity. Switching to HTTPS adds SSL/TLS encryption, authentication, and integrity protection. The author notes that HTTPS requires certificates, which may incur costs.
10. Data Encryption
Sensitive fields (phone, email, password, ID, bank card) should be encrypted at rest using AES symmetric encryption. Custom annotations on entity fields allow MyBatis interceptors to encrypt on write and decrypt on read. Masking (e.g., 182***3457) is applied when displaying partial data.
11. Risk Control
Login endpoints should record failed attempts in Redis. After three consecutive failures, present a harder captcha; after ten failures within a day, lock the account. Successful logins store IP, city, and device ID. If a subsequent login originates from a vastly different IP or city, treat it as a potential theft and require SMS verification.
These combined measures form a layered defense strategy that mitigates injection, enumeration, brute‑force, and data‑leak risks for modern APIs.
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
