如何在Java或JMeter中生成OAuth 1.0的Nonce、Timestamp和Signature参数
OAuth 1.0 参数生成方案(Java/JMeter,适配LTI请求)
三个参数的基础规则先明确:
- Nonce:单次请求唯一的随机字符串,用于防重放,长度无强制要求,一般用32位无符号随机字母数字串即可
- Timestamp:Unix时间戳,单位为秒,和服务端时间差通常不能超过5分钟,否则会被判定为请求过期
- Signature:基于HMAC-SHA1算法生成,所有请求参数(含LTI自定义参数、oauth_前缀参数,不含signature本身)都需要参与计算
Java 实现
不需要引入额外第三方包也可以实现,示例代码如下:
import java.net.URLEncoder; import java.security.SecureRandom; import java.util.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class OAuth1Generator { private static final String OAUTH_SIGNATURE_METHOD = "HMAC-SHA1"; private static final String OAUTH_VERSION = "1.0"; private static final String ENCODING = "UTF-8"; // 生成Nonce public static String generateNonce() { SecureRandom random = new SecureRandom(); byte[] nonceBytes = new byte[16]; random.nextBytes(nonceBytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(nonceBytes); } // 生成Timestamp public static String generateTimestamp() { return String.valueOf(System.currentTimeMillis() / 1000); } // 生成Signature public static String generateSignature(String requestMethod, String requestUrl, String consumerKey, String consumerSecret, String nonce, String timestamp, Map<String, String> customParams) throws Exception { // 1. 收集所有需要参与签名的参数 Map<String, String> allParams = new HashMap<>(customParams); allParams.put("oauth_consumer_key", consumerKey); allParams.put("oauth_nonce", nonce); allParams.put("oauth_signature_method", OAUTH_SIGNATURE_METHOD); allParams.put("oauth_timestamp", timestamp); allParams.put("oauth_version", OAUTH_VERSION); // 2. 参数编码 + 字典序排序 List<String> paramList = new ArrayList<>(); for (Map.Entry<String, String> entry : allParams.entrySet()) { String encodedKey = encode(entry.getKey()); String encodedValue = encode(entry.getValue()); paramList.add(encodedKey + "=" + encodedValue); } Collections.sort(paramList); String paramStr = String.join("&", paramList); // 3. 拼接签名基串 String baseString = String.join("&", encode(requestMethod.toUpperCase()), encode(requestUrl), encode(paramStr) ); // 4. 生成密钥,无token的场景末尾直接加& String secret = encode(consumerSecret) + "&"; SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(ENCODING), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] signatureBytes = mac.doFinal(baseString.getBytes(ENCODING)); // 5. Base64编码得到最终签名 return Base64.getEncoder().encodeToString(signatureBytes); } // 符合RFC3986的URL编码,替换URLEncoder默认的空格转+为%20 private static String encode(String content) throws Exception { return URLEncoder.encode(content, ENCODING) .replace("+", "%20") .replace("*", "%2A") .replace("%7E", "~"); } }
使用时把LTI请求的所有自定义参数放到customParams里传入即可,生成的三个参数直接加到请求参数里就行。
JMeter 实现
直接在LTI请求前添加JSR223 PreProcessor,语言选择Groovy,把以下脚本粘贴进去即可,生成的参数会自动存为JMeter变量,在请求里直接用${oauth_nonce}、${oauth_timestamp}、${oauth_signature}引用即可。
import java.net.URLEncoder import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec // 配置项,替换成你自己的参数 String consumerKey = "你的ConsumerKey" String consumerSecret = "你的ConsumerSecret" String requestMethod = "POST" // LTI请求一般都是POST String requestUrl = "你的LTI请求地址" // 这里放你LTI的所有自定义参数 Map customParams = [ "lti_message_type": "basic-lti-launch-request", "lti_version": "LTI-1p0", "resource_link_id": "your_resource_id" ] // 生成nonce String nonce = UUID.randomUUID().toString().replace("-", "") vars.put("oauth_nonce", nonce) // 生成timestamp String timestamp = String.valueOf(System.currentTimeMillis() / 1000) vars.put("oauth_timestamp", timestamp) // 计算signature Map allParams = new HashMap(customParams) allParams.put("oauth_consumer_key", consumerKey) allParams.put("oauth_nonce", nonce) allParams.put("oauth_signature_method", "HMAC-SHA1") allParams.put("oauth_timestamp", timestamp) allParams.put("oauth_version", "1.0") // 编码+排序参数 def encode = { str -> return URLEncoder.encode(str, "UTF-8") .replace("+", "%20") .replace("*", "%2A") .replace("%7E", "~") } List paramList = [] allParams.each { k, v -> paramList.add(encode(k) + "=" + encode(v as String)) } Collections.sort(paramList) String paramStr = paramList.join("&") // 拼接签名基串 String baseString = [encode(requestMethod.toUpperCase()), encode(requestUrl), encode(paramStr)].join("&") // 加密生成签名 String secret = encode(consumerSecret) + "&" SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1") Mac mac = Mac.getInstance("HmacSHA1") mac.init(keySpec) byte[] signatureBytes = mac.doFinal(baseString.getBytes("UTF-8")) String signature = Base64.getEncoder().encodeToString(signatureBytes) vars.put("oauth_signature", signature)
注意事项
- LTI的所有自定义参数必须全部参与签名计算,漏传会导致签名校验失败
- 请求URL必须是不带查询参数的完整地址,如果有查询参数,需要把参数拆分出来放到customParams里参与签名
- 时间戳必须是秒级,不要传毫秒级时间戳,否则会直接校验失败
内容的提问来源于stack exchange,提问作者SanjayDVG
相关产品推荐
相关产品推荐

