API Security: HMAC Signatures, Anti-Replay & Idempotency with Spring Boot & Redisson
This article provides a comprehensive implementation guide for securing APIs using HMAC-SHA256 signatures, timestamp and nonce anti-replay mechanisms, appId/appSecret credential management, constant-time comparison to prevent timing attacks, and business idempotency patterns with Spring Boot 3.2.4 and Redisson.
Complete Implementation (Spring Boot 3.2.4 + Redisson)
9.1 Request Header and Parameter Specification
The caller sends requests with the following parameters:
appId (query or header): Caller identifier, public
timestamp (query or header): Request timestamp in milliseconds
nonce (query or header): One-time random number
sign (header): HMAC-SHA256 signature
POST /api/pay?appId=APP001×tamp=1730000000000&nonce=a1b2c3d4
X-Sign: 8a7f... (HMAC signature)
Content-Type: application/json
{"orderId": 1, "amount": 100}9.2 Signature Verification Service
@Service
public class ApiSignService {
@Autowired
private AppCredentialRepository appRepo;
@Autowired
private RedissonClient redisson;
private static final long MAX_SKEW = 60_000L; // clock skew 60 seconds
private static final long VALID_WINDOW = 5 * 60_000L; // validity 5 minutes
private static final Duration NONCE_TTL = Duration.ofMinutes(6); // nonce stored 6 minutes
/** Verify request signature */
public void verify(SignContext ctx) {
// 1. Look up appSecret
String appSecret = appRepo.findSecretByAppId(ctx.getAppId());
if (appSecret == null) {
throw new ApiException(401, "Invalid appId");
}
// 2. Timestamp validation (prevent long-term replay + future time)
long now = System.currentTimeMillis();
if (Math.abs(now - ctx.getTimestamp()) > MAX_SKEW + VALID_WINDOW) {
throw new ApiException(401, "Request expired");
}
if (ctx.getTimestamp() - now > MAX_SKEW) {
throw new ApiException(401, "Abnormal request time");
}
// 3. Nonce validation (SETNX atomic operation, prevent short-term replay)
RBucket<String> nonceBucket = redisson.getBucket("api:nonce:" + ctx.getNonce());
if (!nonceBucket.setIfAbsent("1", NONCE_TTL)) {
throw new ApiException(401, "Duplicate request");
}
// 4. Recompute signature and constant-time comparison
String signString = SignatureUtil.buildSignString(
ctx.getMethod(), ctx.getPath(), ctx.getQuery(),
ctx.getBody(), ctx.getAppId(), ctx.getTimestamp(), ctx.getNonce());
String expected = SignatureUtil.sign(appSecret, signString);
if (!SignatureUtil.constantTimeEquals(expected, ctx.getSign())) {
throw new ApiException(401, "Signature mismatch");
}
}
}9.3 Signature Interceptor
@Component
public class ApiSignInterceptor implements HandlerInterceptor {
@Autowired
private ApiSignService signService;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
// Only intercept endpoints requiring signature
if (!(handler instanceof HandlerMethod hm)) return true;
if (!hm.hasMethodAnnotation(RequireSign.class)) return true;
// Wrap request body (body can only be read once, cache for signature recomputation and downstream business)
CachedBodyHttpServletRequest wrapped = new CachedBodyHttpServletRequest(req);
SignContext ctx = SignContext.builder()
.appId(req.getParameter("appId"))
.timestamp(Long.parseLong(req.getParameter("timestamp")))
.nonce(req.getParameter("nonce"))
.sign(req.getHeader("X-Sign"))
.method(req.getMethod())
.path(req.getRequestURI())
.query(extractQuery(req))
.body(wrapped.getBody())
.build();
signService.verify(ctx);
req.setAttribute("cachedBody", wrapped); // pass to downstream
return true;
}
private Map<String, String> extractQuery(HttpServletRequest req) {
Map<String, String> map = new HashMap<>();
req.getParameterMap().forEach((k, v) -> map.put(k, v[0]));
return map;
}
}Business interface usage:
@RequireSign
@PostMapping("/api/pay")
public PayResult pay(@RequestBody PayRequest body) {
return payService.pay(body);
}9.4 Body Caching Wrapper
HTTP request body is a stream, readable only once. Signature verification needs to read body to recompute signature, and downstream business also needs to read body, so we wrap and cache:
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private final byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest req) throws IOException {
super(req);
this.cachedBody = req.getInputStream().readAllBytes();
}
public String getBody() {
return new String(cachedBody, StandardCharsets.UTF_8);
}
@Override
public ServletInputStream getInputStream() {
ByteArrayInputStream bis = new ByteArrayInputStream(cachedBody);
return new ServletInputStream() {
@Override
public int read() { return bis.read(); }
@Override
public boolean isFinished() { return bis.available() == 0; }
@Override
public boolean isReady() { return true; }
@Override
public void setReadListener(ReadListener l) {}
};
}
}Core Five: appId and appSecret
10.1 Their Roles
appId : Identifies caller identity; Public (can be in header/query)
appSecret : Key for computing signature; Absolutely secret (never transmitted)
10.2 Why appSecret Must Not Be Transmitted
appSecret is used locally to compute HMAC signature , both caller and callee use the same appSecret to compute:
Caller computes signature with appSecret, sends only the signature, not appSecret
Backend looks up appSecret by appId, recomputes signature for comparison
appSecret never travels on the network; intercepted requests yield no appSecret
If appSecret is transmitted : a man-in-the-middle could forge arbitrary signatures, completely breaking the signature mechanism. appSecret must exist only locally on both ends, never on the network.
10.3 Key Management
Not in code : appSecret stored in config center/Vault, not hardcoded
Regular rotation : quarterly rotation, support multi-version key coexistence (new key signs, old key still verifies, retire old after transition)
Least privilege : each appId granted only necessary interface permissions
Audit : full audit trail of appSecret access
10.4 Multi-Version Key Coexistence
Key rotation cannot be a hard cut — requests signed with old key may still be in flight; immediately retiring old key would reject valid requests. Multi-version coexistence:
public String findSecretByAppId(String appId) {
// Return list of currently valid keys (new and old coexist)
List<AppCredential> creds = appRepo.findActiveByAppId(appId);
// During verification, try each; any match passes (transition period both old and new work)
...
}Core Six: Constant-Time Comparison to Prevent Timing Attacks
11.1 Timing Attack Principle
Ordinary String.equals returns false at the first differing character. An attacker measuring response time can brute-force the signature character by character:
Attacker tries signatures:
1st char correct → comparison proceeds to 2nd char → slightly slower response
1st char wrong → returns at 1st char → slightly faster response
Thus brute-force per character, complexity drops from O(16^32) to O(16*32)Principle : equals comparison is "short-circuit" — returns on first difference, skipping rest. Response time therefore leaks "first N chars match". Attacker fixes first char (response slows when correct), then second char... reducing exponential difficulty to linear.
11.2 Constant-Time Comparison
Regardless of where difference occurs, traverse entire string, consistent timing:
public static boolean constantTimeEquals(String a, String b) {
if (a == null || b == null) return false;
if (a.length() != b.length()) return false;
int result = 0;
for (int i = 0; i < a.length(); i++) {
result |= a.charAt(i) ^ b.charAt(i); // XOR accumulate per char
}
return result == 0; // all same → result==0
}Principle : XOR (same=0, different≠0) accumulates per bit, finally check if accumulated result is all 0. Any difference forces full traversal, consistent timing, no leakage of "first N chars match".
Key : Any comparison involving secrets/signatures/tokens/hashes must use constant-time comparison to prevent timing attacks. This is a fundamental secure coding principle.
11.3 Applicable Scenarios
Password hash comparison: Yes
API signature comparison: Yes
Token comparison: Yes
HMAC comparison: Yes
Ordinary business field comparison (e.g., username): No (no secret, timing attack meaningless)
Core Seven: Nonce Anti-Replay and Business Idempotency
12.1 Difference Between the Two
nonce : Prevents malicious replay (attacker intercepts and resends); Gateway layer; Request-level (reject duplicate requests)
Business idempotency : Prevents network retries causing duplicates (caller actively resends); Business layer; Business-level (duplicate execution yields same result)
Difference :
nonce is "reject duplicate requests", fast fail, prevents attacker malicious replay (short-term high frequency)
Idempotency is "duplicate execution produces no side effects", prevents network instability causing caller retries (legitimate resends)
12.2 Relationship: Complementary, Not Substitutive
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.
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.
