optimize HTTP接口签名功能 防重放攻击从nonce -> appId+nonce维度

pull/130/head
1351515658@qq.com 2024-07-31 11:35:07 +08:00
parent 9194e094e6
commit 99bef36c90
3 changed files with 10 additions and 10 deletions

View File

@ -69,7 +69,7 @@ public class ApiSignatureAspect {
// 3. 将 nonce 记入缓存,防止重复使用(重点二:此处需要将 ttl 设定为允许 timestamp 时间差的值 x 2
String nonce = request.getHeader(signature.nonce());
signatureRedisDAO.setNonce(nonce, signature.timeout() * 2, signature.timeUnit());
signatureRedisDAO.setNonce(appId, nonce, signature.timeout() * 2, signature.timeUnit());
return true;
}
@ -113,7 +113,7 @@ public class ApiSignatureAspect {
}
// 3. 检查 nonce 是否存在,有且仅能使用一次
return signatureRedisDAO.getNonce(nonce) == null;
return signatureRedisDAO.getNonce(appId, nonce) == null;
}
/**

View File

@ -22,7 +22,7 @@ public class ApiSignatureRedisDAO {
* VALUE String
*
*/
private static final String SIGNATURE_NONCE = "api_signature_nonce:%s";
private static final String SIGNATURE_NONCE = "api_signature_nonce:%s:%s";
/**
*
@ -36,16 +36,16 @@ public class ApiSignatureRedisDAO {
// ========== 验签随机数 ==========
public String getNonce(String nonce) {
return stringRedisTemplate.opsForValue().get(formatNonceKey(nonce));
public String getNonce(String appId, String nonce) {
return stringRedisTemplate.opsForValue().get(formatNonceKey(appId, nonce));
}
public void setNonce(String nonce, int time, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(formatNonceKey(nonce), "", time, timeUnit);
public void setNonce(String appId, String nonce, int time, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(formatNonceKey(appId, nonce), "", time, timeUnit);
}
private static String formatNonceKey(String key) {
return String.format(SIGNATURE_NONCE, key);
private static String formatNonceKey(String appId, String nonce) {
return String.format(SIGNATURE_NONCE, appId, nonce);
}
// ========== 签名密钥 ==========

View File

@ -69,7 +69,7 @@ public class ApiSignatureTest {
// 断言结果
assertTrue(result);
// 断言调用
verify(signatureRedisDAO).setNonce(eq(nonce), eq(120), eq(TimeUnit.SECONDS));
verify(signatureRedisDAO).setNonce(eq(appId),eq(nonce), eq(120), eq(TimeUnit.SECONDS));
}
}