You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JMeter的WS-Security中添加指定格式的Timestamp元素?

在JMeter中给WS-Security添加Timestamp元素的解决方法

我之前也碰到过一模一样的问题——JMeter的SOAP Message Signer组件默认不会自动生成你需要的<wsu:Timestamp>元素,得配合其他组件或者自定义脚本才能实现,下面是我亲测有效的两种方案:

方案一:用JMeter自带的WS Security Timestamp预处理器

这是最省心的官方方案,专门用来生成符合WS-Security规范的Timestamp:

  1. 在你的SOAP请求(比如HTTP Request或SOAP/XML-RPC Request)上右键,选择 Add → Pre Processors → WS Security Timestamp
  2. 配置预处理器的关键参数:
    • 设置Created的时间偏移为0(用当前UTC时间),Expires根据需求设置,比如3600(1小时后过期)
    • 勾选「Add wsu:Id」选项,这样会自动生成类似TS-C5B52CA211571174C9151739434007851的唯一ID
    • 确认命名空间wsu对应的URL是http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd(预处理器默认会填,但最好检查一下)
  3. 配置完成后,这个预处理器会自动把Timestamp元素插入到WS-Security标签内部,之后你只需要在SOAP Message Signer的「Elements to Sign」里把Timestamp包含进去即可。

方案二:用JSR223预处理器自定义生成Timestamp

如果官方预处理器满足不了你的自定义需求(比如特殊的格式或ID规则),可以用Groovy脚本手动生成并插入:

  1. 在SOAP请求下添加 JSR223 PreProcessor,选择Groovy作为脚本语言(性能最优)
  2. 复制下面的脚本并根据你的SOAP结构调整:
import java.text.SimpleDateFormat
import java.util.TimeZone
import java.util.UUID

// 生成UTC格式的时间
def dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
def createdTime = dateFormat.format(new Date())
def expiresTime = dateFormat.format(new Date(System.currentTimeMillis() + 3600 * 1000)) // 1小时后过期

// 生成自定义的wsu:Id
def timestampId = "TS-" + UUID.randomUUID().toString().replace("-", "")

// 构建Timestamp元素字符串
def timestampElement = """<wsu:Timestamp wsu:Id="${timestampId}">
    <wsu:Created>${createdTime}</wsu:Created>
    <wsu:Expires>${expiresTime}</wsu:Expires>
</wsu:Timestamp>"""

// 获取原始SOAP请求内容
def originalRequest = sampler.getXmlData()

// 找到WS-Security标签的起始位置,插入Timestamp
def updatedRequest = originalRequest.replace(
    "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">",
    "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">${timestampElement}"
)

// 更新请求内容
sampler.setXmlData(updatedRequest)

注意:要根据你实际的WS-Security标签的命名空间和格式,调整replace方法里的匹配字符串,确保能精准插入到WS-Security内部。

关键注意事项

  • 不管用哪种方案,都要在SOAP Message Signer的「Elements to Sign」中添加Timestamp的wsu:Id(或者用XPath表达式定位),确保签名范围包含该元素
  • 必须在SOAP信封的根元素中声明wsu命名空间,比如:<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">,否则Timestamp元素会出现命名空间错误
  • 测试时用「View Results Tree」查看请求内容,确认Timestamp已经正确插入到WS-Security块中,再验证签名是否生效

内容的提问来源于stack exchange,提问作者miguel lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:35:45