• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JMeter前端使用JMeter测试JSEncrypt加密登录

武飞扬头像
节省钱
帮助1

前端使用JMeter测试JSEncrypt加密登录

简介:前端开发时会接触到用户登录,登录时为了数据的安全会使用到jsencrypt加密工具,同时我们需要使用jmeter来进行压测,帮助我们了解Web应用程序在高负载情况下的性能表现,从而为优化应用程序性能提供参考

环境:

1.JMeter: 5.5
2.JDK: 8.0
3.插件:
安装插件:jmeter-plugins-manager-1.3.jar
学新通

1.创建线程组

学新通

2. 创建HTTP信息头管理器

学新通

Content-Type :application/json

3. 创建HTTP请求

学新通
3.1请求接口说明requestBody:
loginType登录类型,phone登录的手机号,password加密后的密码

{
	"loginType":0, 
	"phone":"${username}",
	"password":"${rsa_pwd}"
}

4. 添加前置处理器

4.1 添加csv文件

学新通
学新通

4.2 添加JSR223预处理程序

4.2.1 获取公钥并保存

学新通
脚本:

// 导入必需的类
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

// 创建一个 HTTPS 连接
def httpClient = HttpClients.createDefault()

// 创建一个 HTTP GET 请求
def httpRequest = new HttpGet("https://XXXXX.com/auth-server/oauth/publickey")

// 发送 HTTP GET 请求并获取响应
def httpResponse = httpClient.execute(httpRequest)

// 获取响应数据
def response = EntityUtils.toString(httpResponse.getEntity())

// 将响应数据保存到 JMeter 变量中
vars.put("response", response)

// 关闭连接
httpClient.close()

学新通
4.2.2 加密用户的密码

学新通


var log = org.apache.logging.log4j.LogManager.getLogger();
var response = vars.get("response");
var navigator = this;
var window = this;


// 引用在线jsencrypt.min.js包,也可以下载到本地再引用
load("https://passport.cnblogs.com/scripts/jsencrypt.min.js");

log.info("==================================开始加密==============================");
// 获取公钥
var pubKey = JSON.parse(response).data; 
log.info("公钥:" pubKey);

// 使用JSEncrypt库对数据进行加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubKey);

// 用户名
var username = '${phone}'; 
log.info("用户名:" username);
// 将用户名保存到 JMeter 变量中
vars.put("username", username)

// 获取密码
var password = '${password}'; 
log.info("密码:" password);

// 获取当前时间戳
var currentTime = new Date().getTime(); 
log.info("当前时间戳:" currentTime);

// 将密码和当前时间进行拼接
var data = password   ","   currentTime;
var rsa_pwd = encrypt.encrypt(data);
log.info("加密后数据:" rsa_pwd);


// 将加密后数据保存到 JMeter 变量中
vars.put("rsa_pwd", rsa_pwd)

log.info("==================================结束加密==============================");

学新通

5. 添加-断言-JSON断言

学新通

6.添加-后置处理器-JSON提取器

提取登录成功后,后端返回的token
学新通

7.添加-监听器-察看结果树

学新通

8.添加-监听器-聚合报告

学新通

9.开始测试

9.1接口响应结果:

学新通

9.2聚合报告:

学新通
补充:你也可以直接使用我配置好的jmx文件,在jmeter中直接打开即可:

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.5">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="测试计划" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="用户定义的变量" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ResultCollector guiclass="StatVisualizer" testclass="ResultCollector" testname="聚合报告" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <url>true</url>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
      </ResultCollector>
      <hashTree/>
      <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="察看结果树" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <url>true</url>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
      </ResultCollector>
      <hashTree/>
      <kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="jp@gc - PerfMon Metrics Collector" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <url>true</url>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
        <longProp name="interval_grouping">1000</longProp>
        <boolProp name="graph_aggregated">false</boolProp>
        <stringProp name="include_sample_labels"></stringProp>
        <stringProp name="exclude_sample_labels"></stringProp>
        <stringProp name="start_offset"></stringProp>
        <stringProp name="end_offset"></stringProp>
        <boolProp name="include_checkbox_state">false</boolProp>
        <boolProp name="exclude_checkbox_state">false</boolProp>
        <collectionProp name="metricConnections">
          <collectionProp name="-1338873306">
            <stringProp name="645947445">xxxxxx.com</stringProp>
            <stringProp name="0"></stringProp>
            <stringProp name="66952">CPU</stringProp>
            <stringProp name="0"></stringProp>
          </collectionProp>
          <collectionProp name="655379669">
            <stringProp name="645947445">xxxxxx.com</stringProp>
            <stringProp name="0"></stringProp>
            <stringProp name="-1993889503">Memory</stringProp>
            <stringProp name="0"></stringProp>
          </collectionProp>
          <collectionProp name="767719685">
            <stringProp name="645947445">xxxxxx.com</stringProp>
            <stringProp name="0"></stringProp>
            <stringProp name="-274342153">Network I/O</stringProp>
            <stringProp name="0"></stringProp>
          </collectionProp>
        </collectionProp>
      </kg.apc.jmeter.perfmon.PerfMonCollector>
      <hashTree/>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="线程组" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="循环控制器" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">10</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
        <boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
      </ThreadGroup>
      <hashTree>
        <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="HTTP信息头管理器" enabled="true">
          <collectionProp name="HeaderManager.headers">
            <elementProp name="Content-Type" elementType="Header">
              <stringProp name="Header.name">Content-Type</stringProp>
              <stringProp name="Header.value">application/json</stringProp>
            </elementProp>
          </collectionProp>
        </HeaderManager>
        <hashTree/>
        <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="login" enabled="true">
          <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
          <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
            <collectionProp name="Arguments.arguments">
              <elementProp name="" elementType="HTTPArgument">
                <boolProp name="HTTPArgument.always_encode">false</boolProp>
                <stringProp name="Argument.value">{&#xd;
	&quot;loginType&quot;:0,&#xd;
	&quot;phone&quot;:&quot;${username}&quot;,&#xd;
	&quot;password&quot;:&quot;${rsa_pwd}&quot;&#xd;
}</stringProp>
                <stringProp name="Argument.metadata">=</stringProp>
              </elementProp>
            </collectionProp>
          </elementProp>
          <stringProp name="HTTPSampler.domain">xxxxxx.com</stringProp>
          <stringProp name="HTTPSampler.port"></stringProp>
          <stringProp name="HTTPSampler.protocol">https</stringProp>
          <stringProp name="HTTPSampler.contentEncoding"></stringProp>
          <stringProp name="HTTPSampler.path">/auth-server/oauth/login</stringProp>
          <stringProp name="HTTPSampler.method">POST</stringProp>
          <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
          <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
          <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
          <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
          <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
          <stringProp name="HTTPSampler.connect_timeout"></stringProp>
          <stringProp name="HTTPSampler.response_timeout"></stringProp>
        </HTTPSamplerProxy>
        <hashTree>
          <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="CSV 数据文件设置" enabled="true">
            <stringProp name="delimiter">,</stringProp>
            <stringProp name="fileEncoding">UTF-8</stringProp>
            <stringProp name="filename">C:/Users/chenhongxin/Desktop/20用户.csv</stringProp>
            <boolProp name="ignoreFirstLine">true</boolProp>
            <boolProp name="quotedData">false</boolProp>
            <boolProp name="recycle">false</boolProp>
            <stringProp name="shareMode">shareMode.all</stringProp>
            <boolProp name="stopThread">true</boolProp>
            <stringProp name="variableNames">phone,password</stringProp>
          </CSVDataSet>
          <hashTree/>
          <JSR223PreProcessor guiclass="TestBeanGUI" testclass="JSR223PreProcessor" testname="获取公钥并保存" enabled="true">
            <stringProp name="scriptLanguage">groovy</stringProp>
            <stringProp name="parameters"></stringProp>
            <stringProp name="filename"></stringProp>
            <stringProp name="cacheKey">true</stringProp>
            <stringProp name="script">// 导入必需的类
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

// 创建一个 HTTPS 连接
def httpClient = HttpClients.createDefault()

// 创建一个 HTTP GET 请求
def httpRequest = new HttpGet(&quot;https://xxxxxx.com/auth-server/oauth/publickey&quot;)

// 发送 HTTP GET 请求并获取响应
def httpResponse = httpClient.execute(httpRequest)

// 获取响应数据
def response = EntityUtils.toString(httpResponse.getEntity())

// 将响应数据保存到 JMeter 变量中
vars.put(&quot;response&quot;, response)

// 关闭连接
httpClient.close()
</stringProp>
          </JSR223PreProcessor>
          <hashTree/>
          <JSR223PreProcessor guiclass="TestBeanGUI" testclass="JSR223PreProcessor" testname="加密用户的密码" enabled="true">
            <stringProp name="scriptLanguage">javascript</stringProp>
            <stringProp name="parameters"></stringProp>
            <stringProp name="filename"></stringProp>
            <stringProp name="cacheKey">true</stringProp>
            <stringProp name="script">
var log = org.apache.logging.log4j.LogManager.getLogger();
var response = vars.get(&quot;response&quot;);
var navigator = this;
var window = this;


// 引用在线jsencrypt.min.js包,也可以下载到本地再引用
load(&quot;https://passport.cnblogs.com/scripts/jsencrypt.min.js&quot;);



log.info(&quot;==================================开始加密==============================&quot;);
// 获取公钥
var pubKey = JSON.parse(response).data; 
log.info(&quot;公钥:&quot; pubKey);

// 使用JSEncrypt库对数据进行加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubKey);

// 用户名
var username = &apos;${phone}&apos;; 
log.info(&quot;用户名:&quot; username);
// 将用户名保存到 JMeter 变量中
vars.put(&quot;username&quot;, username)

// 获取密码
var password = &apos;${password}&apos;; 
log.info(&quot;密码:&quot; password);

// 获取当前时间戳
var currentTime = new Date().getTime(); 
log.info(&quot;当前时间戳:&quot; currentTime);

// 将密码和当前时间进行拼接
var data = password   &quot;,&quot;   currentTime;
var rsa_pwd = encrypt.encrypt(data);
log.info(&quot;加密后数据:&quot; rsa_pwd);


// 将加密后数据保存到 JMeter 变量中
vars.put(&quot;rsa_pwd&quot;, rsa_pwd)

log.info(&quot;==================================结束加密==============================&quot;);

//

//
 将加密后的密码和用户名添加到HTTP请求参数中
//vars.put(&quot;rsa_pwd&quot;, rsa_pwd);
//vars.put(&quot;username&quot;, username);
//
//
</stringProp>
          </JSR223PreProcessor>
          <hashTree/>
          <JSONPathAssertion guiclass="JSONPathAssertionGui" testclass="JSONPathAssertion" testname="JSON断言" enabled="true">
            <stringProp name="JSON_PATH">$.code</stringProp>
            <stringProp name="EXPECTED_VALUE">200</stringProp>
            <boolProp name="JSONVALIDATION">true</boolProp>
            <boolProp name="EXPECT_NULL">false</boolProp>
            <boolProp name="INVERT">false</boolProp>
            <boolProp name="ISREGEX">true</boolProp>
          </JSONPathAssertion>
          <hashTree/>
          <JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="JSON提取器" enabled="true">
            <stringProp name="JSONPostProcessor.referenceNames">token</stringProp>
            <stringProp name="JSONPostProcessor.jsonPathExprs">$.data.token</stringProp>
            <stringProp name="JSONPostProcessor.match_numbers">1</stringProp>
          </JSONPostProcessor>
          <hashTree/>
        </hashTree>
        <DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="调试取样器${token}" enabled="false">
          <boolProp name="displayJMeterProperties">false</boolProp>
          <boolProp name="displayJMeterVariables">true</boolProp>
          <boolProp name="displaySystemProperties">false</boolProp>
        </DebugSampler>
        <hashTree/>
      </hashTree>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgaegeh
系列文章
更多 icon
同类精品
更多 icon
继续加载