简体   繁体   English

如何在 JMeter 中手动设置由 JavaScript 以编程方式设置的 cookie

[英]How to manually set a cookie in JMeter that is set programmatically by JavaScript

I am testing a web application which has a following flow:我正在测试具有以下流程的 Web 应用程序:

  1. User logs in用户登录
  2. On successful login, an access token is issued.成功登录后,将颁发访问令牌。
  3. Every request after login has the access token to get a resource.登录后的每个请求都具有访问令牌以获取资源。

In my JMeter test plan, I added a cookie manager and I could extract this access token from the response header of the login request.在我的 JMeter 测试计划中,我添加了一个 cookie 管理器,我可以从登录请求的响应标头中提取此访问令牌。 I want to set this access token as a cookie the test plan.我想将此访问令牌设置为测试计划的 cookie。

I added this after extracting the access token in a BSF PostProcessor: vars.put('COOKIE_access_token', actual_token);我在 BSF 后处理器中提取访问令牌后添加了这个: vars.put('COOKIE_access_token', actual_token); and it is seen as a cookie variable in the debug sampler.它在调试采样器中被视为 cookie 变量。

在此处输入图像描述

But the subsequent requests after login do not have this access token in their cookie data, and as a result are again redirected to login page.但是登录后的后续请求在其 cookie 数据中没有此访问令牌,因此再次重定向到登录页面。

How can I set this token as a cookie which will be used for all further requests?如何将此令牌设置为将用于所有进一步请求的 cookie?

Defining variable does not add the cookie itself.定义变量不会添加 cookie 本身。 You need to insert cookie into Cookie Manager to make this work, like:您需要将 cookie 插入 Cookie 管理器才能使其正常工作,例如:

  1. Add a Beanshell PreProcessor as a child of the request which fails添加一个Beanshell 预处理器作为失败请求的子项
  2. Put the following code into the PreProcessor's "Script" area:将以下代码放入 PreProcessor 的“脚本”区域:

     import org.apache.jmeter.protocol.http.control.Cookie; sampler.getCookieManager().add(new Cookie("access_token", "actual_token", "domain", "path", true, Long.MAX_VALUE));

Replace domain , path , true (stands for "secure") and Long.MAX_VALUE (expires) with your own values.用您自己的值替换domainpathtrue (代表“安全”)和Long.MAX_VALUE (过期)。

See How to Use BeanShell: JMeter's Favorite Built-in Component for example of manipulating cookies programatically.有关以编程方式操作 cookie 的示例,请参阅如何使用 BeanShell:JMeter 最喜欢的内置组件

import org.apache.jmeter.protocol.http.control.Cookie;

sampler.getCookieManager().add(new Cookie("access_token", "actual_token", "domain", "path", true, Long.MAX_VALUE));

This code really worked.这段代码确实有效。 This helped me.这对我有帮助。
Who ever wants to pass missing cookie(session or any cookies) in request cookie data, instead of adding header manager please use the above code in bean shell pre processor.谁想要在请求 cookie 数据中传递丢失的 cookie(会话或任何 cookie),而不是添加标头管理器,请在 bean shell 预处理器中使用上面的代码。

Thank you DMITRI T谢谢德米特里 T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM