I am load testing an API using Jmeter. The Header of the request has an authentication request which needs me to Base64 the url+Nonce+Unix timestamp and SHA256 the resultant value with a secret key.
The above needs to be passed in header along with Nonce and timestamp.
For the above scenario should I create a custom function or use any preprocessor ?
You can do it via Beanshell PreProcessor as follows:
Add a HTTP Header Manager as a child of your HTTP Request sampler
Add aforementioned Beanshell PreProcessor the same way
Put the following code into the PreProcessor's "Script" area:
import org.apache.commons.httpclient.auth.DigestScheme; // necessary imports
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.jmeter.protocol.http.control.Header;
String url = sampler.getUrl().toString(); // get URL
String nonce = DigestScheme.createCnonce(); // get nonce
long timestamp = System.currentTimeMillis() / 1000L;
String combined = url + nonce + timestamp; // put everything together
byte[] base64 = Base64.encodeBase64(combined.getBytes()); // encode as Base64
String headerValue = DigestUtils.sha256Hex(base64); // encode SHA256
sampler.getHeaderManager().add(new Header("headerName", headerValue)); // add generated header to request
sampler here is a shorthand reference to parent HTTP Request Sampler class which I believe is HTTPSamplerProxy so its methods are used to get URL and add generated header value.
methods to generate MD5 hash and SHA256 hex are from Apache Commons libraries which are widely used under JMeter's hood.
See How to use BeanShell: JMeter's favorite built-in component guide for more information on using Beanshell scripting in JMeter tests.
Your best bet is to use a BSF Pre-Processor in JavaScript mode to do everything the client normally would. You'll have to take the client JS and modify it to work without FORM data.
You can build the entire header in JS exactly like a client would. BSF Pre-Processor allows you to access jmeter run-time variables, so you would create a new one to store the SHA256 hash value, and use that in a HTTP Header Manager of the sample that needs the authorization.
-Addled
Downloaded eclipse.
Wrote a custom jmeter package.
Exported it as a .jar from eclipse to jmeter lib/ext folder.
Called the package function in beanshell sampler
Thanks for your answers
#dmitrit's answer is helpful but I needed to do some tweaks to the code to get it to work. Here is what I did:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
String apiKey = vars.get("ApiKey");
String apiSecret = vars.get("ApiSecret");
long timestamp = System.currentTimeMillis() / 1000L;
String combined = apiKey + apiSecret + timestamp;
String generatedSignature = DigestUtils.sha256Hex(combined);
vars.put("GeneratedSignature", generatedSignature);
Note the main differences are:
Most important: DigestUtils.sha256Hex takes a String instead of a byte array. Converting first to bytes screwed up the hash, I think due to padding.
I added the resulting value to vars so it can be used later in Jmeter in the usual way (${GeneratedSignature}).
ApiKey and ApiSecret are defined elsewhere in a Jmeter User Defined Variables element.
With this I was able to make the following work with Mashery in accordance with their authentication instructions posted here.
Related
I already configured the token but I am trying to have a csv file for the login credentials. the login credentials generate code
Try BeanShell processor script to create a base 64 enoded char array and pass that as login credentials.
import org.apache.commons.codec.binary.Base64;
log.info(“Base64 Encoding ClientID & ClientPassword”);
//Create the complete string which needs to be encoded
String forEncoding = vars.get(“ClientID”) + “:” + vars.get(“ClientPassword”);
log.info(“forEncoding: “ + forEncoding);
//Encode the string
byte[] encoded_ClientCredentials = Base64.encodeBase64(forEncoding.getBytes());
//Save the encoded byte array into a String Variable
vars.put(“encoded_ClientCredentials”, new String(encoded_ClientCredentials));
log.info(“encoded_ClientCredentials: “ + vars.get(“encoded_ClientCredentials”));
If you need to provide Base64-encoded credentials you could use __base64Encode() function which is available via Custom JMeter Functions bundle which can be installed using JMeter Plugins Manager
See How to Use the Custom JMeter Functions Plugin article for more details.
From your question it's not really clear how the credentials should be passed, if it's about Basic Access Control it might be much easier to use HTTP Authorization Manager
I am working with Jmeter and Blazemeter in a login script for a web made with Genexus.
The problem that I am having is in the POST.
Whenever I try to make a POST http petition, Jmeter throws the next thing:
As you can see, in the response body, I am having a 440 http error code. This is a login Time-out which means the client's session has expired and must log in again. I used to have a 403 error code but now, after doing some arrangements, I have 440. Do you have any suggestions on how to resolve this?
First, I'm not an expert on Genexus. All my findings are from a black-box point of view.
Genexus Security
I found that Genexus requires at least two things to authenticate on Web Application (I tested only Java and .Net generated apps).
The GXState parameter. This param is sent in post request, and from my understanding works as "Synchronizer token pattern", see more info on Cross-site request forgery. We need to send this param on every post request.
The gxajaxEvt parameter. This is very specific to Genexus Apps. In the documentation mentions this parameter is send encrypted in the URL, and this behavior is managed by the "Javascript debug mode property":
# Javascript Debug Mode: Yes
http://{server}:{port}/{webappname}/servlet/com.{kbname}.{objectname}?gxfullajaxEvt,gx-no-cache=1442811265833
# Javascript Debug Mode: No (default value)
http://{server}:{port}/{webappname}/servlet/com.{kbname}.{objectname}?64df96a2d9b8480aed416e470dae529e,gx-no-cache=1442811265833
JMeter Script
So, to get the GXState, we can use the Regular Expression Extractor:
Name of created variable: GXState
Regular expression: name="GXState" value='(.*?)'
Template: $1$
Match No.: 1
Default Value: NOT_FOUND
The GXState is a JSON, object, from it we can extract the GX_AJAX_KEY to encrypt gxajaxEvt string. Note that, I found the GX_AJAX_KEY is the key used to encrypt in this case, but some others could apply. We can debug this using Browser Web Console, with this:
gx.sec.encrypt("gxajaxEvt")
We'll see something like this:
"8722e2ea52fd44f599d35d1534485d8e206d507a46070a816ca7fcdbe812b0ad"
As we can found, all the client encryption code is in the gxgral.js file. Genexus uses the Rijndael algortihm (Sub set of AES) with block size of 128 bits.
To emulate this client behavior in the JMeter Script we can use the "JSR 233 sampler". A way to get the Rijndael results is use the Bouncy Castle library. We need to add this jar (bouncycastle:bcprov-jdk15to18:1.68) to the JMeter's lib folder to use it.
Our code script will be something like this (Language Groovy 3.0.5/Groovy Scripting Engine 2.0):
import com.jayway.jsonpath.JsonPath
import java.nio.charset.StandardCharsets
import java.util.Arrays
import org.bouncycastle.crypto.BufferedBlockCipher
import org.bouncycastle.crypto.InvalidCipherTextException
import org.bouncycastle.crypto.engines.RijndaelEngine
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.util.encoders.Hex
import org.apache.jmeter.threads.JMeterContextService
import org.apache.jmeter.threads.JMeterContext
import org.apache.jmeter.threads.JMeterVariables
String gxState = vars.get('GXState')
String gxAjaxKey = JsonPath.read(gxState,'$.GX_AJAX_KEY')
byte[] input = Arrays.copyOf('gxajaxEvt'.getBytes(StandardCharsets.UTF_8), 16)
RijndaelEngine engine = new RijndaelEngine(128)
KeyParameter key = new KeyParameter(Hex.decode(gxAjaxKey))
BufferedBlockCipher cipher = new BufferedBlockCipher(engine)
cipher.init(true, key)
byte[] out = new byte[16]
int length = cipher.processBytes(input, 0, 16, out, 0)
cipher.doFinal(out, length)
String encryptedOutput= Hex.toHexString(out)
log.info 'gx.sec.encrypt("gxajaxEvt")='+encryptedOutput
String gxNoCache = String.valueOf(System.currentTimeMillis())
log.info 'gx-no-cache='+gxNoCache
vars.put('gxajaxEvt', encryptedOutput)
vars.put('gxNoCache', gxNoCache)
The script work like this:
First, We get the previos GXState variable extracted.
Second, Using JSON Path (Already available in JMeter 5.4.1) extract the GX_AJAX_KEY property.
Third, We apply the Rijndael algorithm over the gxajaxEvt using the GX_AJAX_KEY as a key.
We also create the gx-no-cache to handle the cache.
With these variables we can send the next request successfully:
We can found this sample JMeter script available here.
For complex scripts, please refer to this guide (Requires GXTest)
In case we get this exception in JMeter ( java.util.zip.ZipException: Not in GZIP format) please refer this answer too.
Any HTTP Status 4xx is a client error, to wit you're sending an incorrect request.
If custom 440 http status code means "session has expired" my expectation is that you have a recorded hard-coded session ID somewhere in your request parameters or headers
You should carefully inspect previous response(s) and look for something which appears to be a session id, once you find it - extract it using a suitable JMeter's Post-Processor and replace hard-coded session ID with the appropriate JMeter Variable. The process is known as correlation
I have test case in my csv file. The request URL has a custom variable.
Sample URL : .../abc/$id
I need to replace this id by the id that we get in response from the previous request. I used json extractor to fetch the id from the response. Now I need to update this id in the next test case request. Fetched the Request URL from jmeter context using below code:
String path = ctx.getCurrentSampler().toString();
path.replaceAll("$id", id);
I am not able to set this updated URL in jmeter context (ctx)
You need to assign new path value to path variable
You need to set sampler path to the new value using sampler.setPath() method
So you need to amend your code like:
String path = ctx.getCurrentSampler().toString();
path = path.replaceAll("$id", id);
sampler.setPath(path);
Demo:
Also consider switching to JSR223 PreProcessor and Groovy language as Groovy performance is much higher, it better supports new Java features and provides some extra "syntax sugar" on top. See Groovy is the New Black article for details.
Try to avoid the pre / post processors if possible.
Your requirement is very simple and straight forward.
Directly use this in the path - assuming id is the name of variable which has the value.
/abc/${id}
I want to extract value of the parameter sent through post request in jmeter.
I know the use of regular expression for extracting response value or request URL but here I would like to extract the value of post request.
I've been thorough how to extract value from request in Jmeter but it didn't worked.
Not sure why do you need it as given you sending "something" you should already have that "something" hence you don't need to extract it, however here you go:
In order to save 1st parameter value (or the whole post data if you use "Body Data" mode):
Add Beanshell PostProcessor as a child of the HTTP Request.
Put the following code into the PostProcessor's "Script" area:
String request = ctx.getCurrentSampler().getArguments().getArgument(0).getValue();
vars.put("request", request);
You will be able to access extracted value as ${request} where required.
Clarifications:
ctx - shorthand for JMeterContext class instance
getCurrentSampler() - in case of HTTP Request sampler stands for HTTPSamplerProxy
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using JMeter and Java API from Beanshell test elements in your JMeter test.
I added a Beanshell PostProcessor in my http request with following code.
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String a = arg.getValue();
vars.put("EMAIL",a);
}
Explanation: I get a my request as a json and put it in EMAIL. Now I can use EMAIL as a variable in my other request.
Then, I added a jp#gc Json Path Extractor and I applied it to a Jmeter Varaible.
Now, Email will be used as variable, which contains my json request and I can extract using jsonPath Extractor.
An easy way to do this is using the JSON Path Extractor.
There are just
For the example you gave
{ "data" : { "name" : "john_doe", } }
'Variable Name: YourNewVar'
'JSON Path: $.data.name'
Should work, but you may need to do some experimenting.
You may want to add a "debug sampler" (its one of the standard samplers) and put in its title $YourNewVar so you can see what is being extracted.
Beanshell and "Regular Expression Extractor" will work, of course, but may be a little harder to use if you are not familiar with them.
have been looking into JMeter recently. I need to get an authentication string from a cookie and use it when posting a request to a different path. The Auth string changes each time the login page is hit.
Is there a way in JMeter to use one cookie for all paths in a test when the paths are different?
IE-
Path to Get Cookie:
Webserver: someURL.net
Path: /some/login/path
Use the cookie value:
Webserver: someURL.net
Path: /somewhere/different
I have set the below JMeter properties to be able to use Cookies as needed.
CookieManager.check.cookies=false
CookieManager.save.cookies=true
CookieManager.allow_variable_cookies=true
When I run the samplers the result for the request to /somewhere/different
Returns [no cookies]
I can see the cookie data present in the Request when the path is /some/login/path
I have tried defining a User-Defined cookie but I need to get the auth string first to use it in the different path.
When I do this I can see the cookie data added to the request to /somewhere/different but the var is not being set. I don't think this is the right way to solve the challenge.
To get the auth string first I tried to use the Controller "User defined Variables" to store the cookie value and pass it back to the Cookie Manager- this did not work.
And I looked at using the RegEx extractor to get the value so I could use it but I'm not sure that this can be used to get cookie values?
My understanding is that you cannot use more than one cookie manager per Thread group. As I type this I realize that the solution might be that I must use separate threads and pass the cookie value from one thread to another.
Apologies if the question is framed poorly first time here, signed up to ask after searches didn't turn up a solution. If you need more info/screens of my JMeter set up for any of the scenarios I tried above I'll add them. And thank you.
I'm afraid you won't be able to manipulate cookies using built-in JMeter features, you'll need to go deeper and invoke JMeter API methods from scripting test elements.
For instance:
Add a Beanshell PostProcessor as a child of the first request
Put the following code into the PostProcessor(s) "Script" area:
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
for (int i = 0; i < manager.getCookieCount(); i++) {
Cookie cookie = manager.get(i);
if (cookie.getName().equals("your_cookie_name")) {
Cookie newCookie = cookie;
newCookie.setPath("/your/new/path");
manager.remove(i);
manager.add(newCookie);
ctx.getCurrentSampler().setCookieManager(manager);
break;
}
}
Change your_cookie_name and /your/new/path as per your requirements
It will create a new one with the different path. JMeter's HTTP Cookie Manager doesn't allow 2 cookies with the same name so the old one has to be removed.
References:
CookieManager class JavaDoc
JMeterContext class JavaDoc
How to Use BeanShell: JMeter's Favorite Built-in Component guide - overview of scripting, extra information on pre-defined variables, "cookbook" with some examples.