11 Essential Techniques to Secure Your APIs: From Validation to Encryption
Learn eleven practical strategies to protect your APIs—including parameter validation, unified response handling, XSS escaping, permission and data access controls, captcha integration, rate limiting, IP whitelisting, sensitive word filtering, HTTPS adoption, data encryption, and risk management—to ensure robust security across your services.
1 Parameter Validation
Ensuring API security starts with thorough validation of request parameters. By checking for null values, correct types, length limits, allowed enum values, and data ranges, most invalid requests can be intercepted. Check if parameter is null: prevent null‑related exceptions. Validate parameter type: reject mismatched types such as a string for an integer field. Validate parameter length: enforce limits to avoid database errors. Validate enum values: ensure values belong to predefined sets. Validate data range: e.g., monetary amounts must be within acceptable bounds.
Custom code or third‑party validation frameworks (e.g., Hibernate Validator with @NotEmpty, @Size, @Max, @Min) can be used, and custom annotations may handle dates or enums.
2 Unified Response Wrapping
Standardizing API responses improves security by preventing internal error details from leaking to external users.
{
"code":0,
"message":null,
"data":[{"id":123,"name":"abc"}]
}The response contains three fields: code: status code (0‑success, 1‑parameter null, 2‑parameter error, 3‑signature error, 4‑timeout, 5‑internal error, etc.). message: user‑friendly message; empty on success. data: actual payload.
Even if a lower‑level exception occurs, the client only receives a generic “internal server error” message. This wrapping can be implemented in an API gateway, which catches business exceptions and converts them to the unified format.
3 XSS Escaping
User‑generated content displayed as HTML (e.g., article details or contracts) must be escaped to prevent XSS attacks. Special characters such as <script>alert("XSS")</script> should be transformed, and a custom annotation with an AOP interceptor can perform the escaping before persisting to the database.
4 Permission Control
APIs need three levels of permission checks:
4.1 Login Verification
Public data can be accessed without authentication, while protected endpoints require checking the current user context for a non‑null user object.
4.2 Functional Permission Control
Critical operations (e.g., order approval) require specific permissions. Custom annotations can declare required permission points, and a gateway interceptor matches the user's permissions against the endpoint.
4.3 Data Permission Control
Different roles see different data subsets. SQL queries can be dynamically appended with data‑scope conditions based on the user's role.
5 Captcha Integration
To mitigate brute‑force attacks on high‑risk endpoints, add image or slider captchas. While complex captchas increase security, they may affect user experience, so a balance is needed.
6 Rate Limiting
Beyond captcha, enforce server‑side rate limits, especially for SMS sending APIs. Store recent send timestamps in a database or Redis, and reject requests that occur within a short interval (e.g., 60 seconds) or exceed a daily quota (e.g., 10 messages per phone number).
7 IP Whitelisting
Critical internal APIs (e.g., membership activation) can restrict access to trusted server IPs via a configurable whitelist, managed through Apollo or a database, ensuring that leaked endpoints remain inaccessible to unauthorized callers.
8 Sensitive Word Filtering
User‑generated text should be checked against a sensitive‑word list (e.g., using HanLP for tokenization). Custom annotations and AOP interceptors can invoke the filter, with a whitelist for false positives.
9 HTTPS Adoption
Replace insecure HTTP with HTTPS to provide encryption, authentication, and integrity. HTTPS combines SSL/TLS with HTTP, protecting data in transit, though it may involve certificate costs.
10 Data Encryption
Sensitive fields such as phone numbers, emails, passwords, ID numbers, and bank cards must be encrypted (e.g., AES symmetric encryption) before storage. Custom annotations and MyBatis interceptors can handle automatic encryption/decryption, and masked display (e.g., 182***3457) can be applied at the presentation layer.
11 Risk Control
Login APIs should incorporate risk controls: track failed attempts in Redis, increase captcha difficulty after multiple failures, lock accounts after excessive errors, and record login IP, city, and device ID. Discrepancies between current and previous login contexts can trigger additional verification such as SMS codes.
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.
