Jmeter通过beanshell对http消息进行签名


1.增加前置beanshell脚本

2.beanshell脚本要点

  • 通过引入外部jar包,引用相关签名算法,如rsa、ecdsa等
  • 通过config.Arguments类的getArgument(0).getValue()获取要发送请求的json body体。调用外部jar包方法进行sha等运算
  • http header的rmv和add操作

3.beanshell代码样例

import com.matrix.common.service.SignatureService;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.config.Arguments;

//获取签名头
public static String getSign(String contentSHA, String date,String nonce ){
    String privateKey = vars.get("privateKey");
    String method = "GET";
    String accept = vars.get("accept");
    String contentType = vars.get("contentType");
    String nonceHeader = "x-bfs-signature-nonce:"+nonce;
    String url = vars.get("createRfqOrderUrl");
    //调用jar包中SignatureService的sign方法进行进行签名
    String signature = SignatureService.sign(privateKey,method,accept,contentSHA, contentType, date, nonceHeader, url);
    return  signature;
}

//发送请求前增加签名相关的Header参数
public static void addHeaders( ){
    //增加日期头
    String date = (new Date()).toString();
    sampler.getHeaderManager().removeHeaderNamed("Date");
    sampler.getHeaderManager().add(new Header("Date",date));
    //增加nonce头
    String nonce = "550e8400e29b41d4a716446655440000";
    
    sampler.getHeaderManager().removeHeaderNamed("x-bfs-signature-nonce");
    sampler.getHeaderManager().add(new Header("x-bfs-signature-nonce",nonce));
    //通过getArgument方法获取json body
    Arguments arguments = sampler.getArguments();
    String content = arguments.getArgument(0).getValue();
    log.info("content="+content);
    //增加Content-SHA256 头
    String contentSHA =      SignatureService.getContentSHA256(content);
    log.info("contentSHA="+contentSHA);
    sampler.getHeaderManager().removeHeaderNamed("Content-SHA256");
    sampler.getHeaderManager().add(new Header("Content-SHA256",contentSHA));
    //增加签名头
    String signature = getSign(contentSHA,date,nonce);
    sampler.getHeaderManager().removeHeaderNamed("Authorization");
    sampler.getHeaderManager().add(new Header("Authorization","bfs "+ vars.get("accessKeyId") +":"+signature));
    return;
}

addHeaders();

你可能感兴趣的:(http,签名,jmeter)