API Request Signature Implementation and Best Practices
This article explains how to protect front‑back separated APIs using a request signature scheme, detailing the required parameters, signature generation algorithm, Java filter implementation, anti‑leech timing checks, nonce usage, and duplicate‑submission prevention with Redis.
In a front‑back separated development model, interfaces become the contract for integration, and protecting these APIs from tampering and replay attacks requires a robust request signature mechanism.
The signature process involves assigning each client an appId and appSecret , adding a timestamp, a nonce, and a signature field to the request header, then verifying them on the server side.
Signature rules :
Assign unique appId and appSecret per caller.
Include a timestamp (valid for 5 minutes).
Include a nonce (at least 10 characters) to prevent duplicate submissions.
Add a signature field containing the signed data.
All dynamic parameters (header, URL, request parameters, and body) are collected, sorted by key, concatenated, and then combined with appSecret before applying an MD5 hash:
signature = DigestUtils.md5DigestAsHex(sortParamsMap + appSecret)The request header must contain the four mandatory fields:
appId=xxxx&nonce=xxxx×tamp=xxxx&sign=xxxExample request URL:
https://mso.xxxx.com.cn/api/user
For GET requests, the query string parameters are considered request parameters; for POST requests, the request body is also included in the signature calculation.
The signature verification filter follows these steps:
Validate the presence of required header parameters.
Collect header, request parameters, URL path, and body, then place them into a sorted map.
Concatenate the sorted values.
Encrypt the concatenated string to generate the sign .
Compare the generated sign with the one sent by the client and reject the request if they differ.
Sample Spring filter implementation:
@Component
public class SignAuthFilter extends OncePerRequestFilter {
static final String FAVICON = "/favicon.ico";
static final String PREFIX = "attack:signature:";
}The filter also checks the timestamp to ensure the request is not older than 10 minutes, preventing link hijacking.
Nonce handling, combined with Redis, detects and blocks duplicate submissions, ensuring each request is processed only once.
Summary : Using a signature scheme secures external APIs against tampering and replay attacks, but it does not encrypt the payload itself; additional measures are needed to protect data confidentiality.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.