Jmeter token refreshing - jmeter

I find the topic Refreshing Auth Token while keep the requests running in JMeter 3.3. I faced with same task - token refreshing each x time and other request sending at the same time. I've seen that author has find the solution. But I would be really appreciated if you could share the logic. I tried with global property in Jmeter, but it seems that I set one token for all users. The timer was allso added, but I'm getting one token for sessions. Probably we have a new solution for Jmeter 5.x. Thanks.

The solution would be the same, you just need to amend it a little bit and use __threadNum() function in order to create thread (virtual user)-specific properties.
Something like:
${__setProperty(token_${__threadNum},variable containing the token,)}
will generate the following JMeter properties:
token_0=token for the first virtual user
token_1=token for the second virtual user
etc.
which can be accessed similarly using __P() function like:
${__P(token_${__threadNum},)}
More information: Here’s What to Do to Combine Multiple JMeter Variables

Thank you so much! I have implemented my script using the following logic in one thread group:
Set var “Trigger” = 60 seconds (token refreshing interval, per minute);
Login user;
Get Token request; and execute actions:
Extract Token and save to vars;
Save “TokenTime” to vars (where “Login” from CSV is the name of property);
Calculate “TokenDiffTime” = “TimeNow- TokenTime” -> Save as property with unique name (the unique name can be the string “Login”+”TimeDiff”- where “Login” is dynamic Login from CSV and “TimeDiff” – just static string; the example of property name is “User1TimeDiff”).
Loop controller with logic:
If Controller (Is token Actual? -> check “TokenDiffTime” >=“Trigger”) -> Call Refresh Token request; Extract actual token.
Invoke App request; using actual token.
If Controller (Is token Actual? -> check “TokenDiffTime” >=“Trigger”) -> Call Refresh Token request; Extract actual token.
Invoke App request; using actual token.
So, such logic takes into account the response time delays and a new app request is invoking with actual token. “Trigger” is flexible value to set token refreshing interval. Hope such topic could be useful to someone.

Related

Does the value of global variable persist in multiple API calls

So I have done a lot of research and could not find a proper answer. This might be a bit long post so sorry for that. I am making a backend API using golang. I am using gingonic for routing and api stuffs.
There are 2 part of the service. Application and user. When lets say createAccount endpoint is called from the other micro service, it need to pass the user information and application token in body. Each application is like micro service that is registered to this micro service that I am building and have a unique token. If the token they pass matches then I will get the id of that row and use that to create an entry in user table which will have the id associate with it.
Now for every API call to this micro service, it is important that they are sending the valid token and that row id is needed to do all sort of functionality like login user, edit user info and so on as the each user is connected with that app id by foreign key. Currently, I wrote a middleware and when any api call is made I get row id and save it to a global variable and then when necessary I am using it in any part of the codebase.
Lets say if 5 multiple API call is made, will that global variable information will be persisted or for each call its brand new value? If it is persisted then what can I do to achieve the brand new of Global variable for every API call or if there are better approach can you please recommend it?
A global variable is not the answer here. It will be overwritten by each request as you suspected. Instead, the typical way to handle this situation is to have a context object that is created within the scope of the HTTP Request and passed to each method that requires knowledge of that context.
One basic rule is to AVOID using the global variables, it is bad practices, you cannot manage the state and you are limited for testing and concurrency using.
In my mind come two basic solutions:
Use context for this. In your handler, add the value in context and propagate this context by all your service calls. It is also useful for tracing if you are working with microservices, then you also should take a look for this. And in the place where you need the value from your global variable, do simple call: ctx.Value(YOUR_KEY) Take a look at the end of the page, you shouldn't use string as the key to context values.
You can wrap your data in the struct with this variable value. For example:
type CreateReq struct {
Token string // value from global variable
User user
}
and use this Token in your services.

JMeter RegUx User Parameters not adding parameter

New to JMeter, and I'm probably missing some simple thing but I can't find it anywhere.
I'm trying to log into a web application so I send a GET request to the home page to retrieve the csrf token and then I use the regular expression extractor to retrieve it:
I then try to place the extracted token into the POST request:
But the extracted token doesn't show up in the request sent via the View Results Tree. Only the UserId and Password are passed which I manually defined:
My regular expression is finding a match as you can see here:
but even if it wasn't finding a match, it should still pass "NotFound" correct?
Any help is greatly appreciated!
Edit: Added a Debug Sampler and it is correctly showing the variable Token with it's correct value. So Token just isn't being added to the request via the RegEx User Parameter Pre Processor.
It's difficult to see what you're doing without seeing the LoginPage step, but you need to make sure you are adding the csrf token you've extracted in the right place.
Typically it could be as a query param, part of a post body or an http header.
As you can see the token has been extracted from your initial response in the Debug sampler, there must be something wrong in how or where the token is being applied to the LoginPage request. (As you say the RegEx User Parameter Pre Processor isn't adding it)
I've never used the PreProcessor and the Jmeter documentation explanation is a bit vague on what it does, but you can add the variables into your request without it using the variable saved for the capture groups - for input name this will be ${Token_g1} and for value it will be ${Token_g2} - which you will be able to see from the Debug Sampler. You'll need to add a Header or Cookie Manager to the Login Page element if this is where the token is.
By setting the template in the Extractor to $1$$2$ you create a variable with the name and value concatenated together. I'm not sure why you would need this, and I would guess that the name doesn't change - in which case you can just use capture group 2, or if you want to use the Variable name Token then update your template to be $2$

Automate sending a request and saving the response

There is a URL which I want to hit and save the response. The URL id needs to be incremented each time and save the response. For example -
First Get Request - http://google.com/getdata/?Id=1
First Response - one
Second Request - http://google.com/getdata/?Id=2
Second Response - two
and so on...
I want to hit the request with increment the id each time and save the response
I have tried using fiddler but unable to figure how to increment the id and save the response.
P.S. - I have to make around 6,00,000 hits
Since the 'Postman' tag is mentioned, I can help you regarding how to implement this in Postman.
Postman has a nice feature of using 'variables'.
You can use environment variables or globals.
Read more about these on their docs:
https://www.getpostman.com/docs/v6/postman/environments_and_globals/variables
You can use a global variable such as 'counter' and set it to 1 / whatever starting point you want.
Then you can modify your request like so :
http://google.com/getdata/?Id={{iteration}}
Now, in the Tests script of the request you can write the following script
let i = parseInt(pm.globals.get('iteration')) + 1;
pm.globals.set('iteration', i);
Also, to access the response you can use the following command in Test script:
console.log(pm.response); // Use pm.response as per your needs
Save the request in a collection.
Now load the Postman's Runner and select the collection.
Now you can put an iteration count of 6,00,000 and hit run!
Remember, heavy iterations will cause performance degradation.
In JMeter you need to click , Ctrl+0 and Ctrl+1 to create , Thread Group and HTTP Request
In Thread Group put the number of hits you need in Number of Threads (users)
In HTTP Request Put in Server Name or IP www.google.com and in Path /getdata/?Id=${__threadNum}
__threadNum will create increasing number from thread 1 to number of hits.
For small number of hits or debugging you can add View Results Tree to view request/response by clicking Ctrl+9 in Test Plan/Thread Group level.
To save the response use Post Processor, especially by adding Regular Expression Extractor below HTTP Request by clicking Ctrl+2.
Allows the user to extract values from a server response using a Perl-type regular expression. As a post-processor, this element will execute after each Sample request in its scope, applying the regular expression, extracting the requested values, generate the template string, and store the result into the given variable name.
Import to notice that for load testing you need to work with non GUI mode, which means call jmeter using command line as jmeter -n -t myTest.jmx
you will use Command-line mode (called Non-GUI mode) to run it for the Load Test.
Don't run load test using GUI mode !
For saving all responses to a one file see save response data or if you want to save file per thread/user you can add Save Responses to a file
Fiddler:
Open script editor (Control + r ) then add the following code inside OnBeforeResponse
static function OnBeforeResponse(oSession: Session) {
if(oSession.oRequest["X-SAVE-ME"] != "")
{
oSession.SaveResponseBody("C:\\tempfiddler\\" + oSession.SuggestedFilename);
}
}
Go to the "Composer" tab and include the header X-SAVE-ME with any value, in the URL, replace your ID with # (just like this: http://google.com/getdata/?Id=#) fiddler will now ask for the starting and ending value of ID before executing;
Please find the snapshot below for your scenario.
Scenario_Testplan
First, go to user properties and put "sample_variables = ID, Response_File_Name" or whatever the name you choose for the variables. Restart jmeter.
Create the below plan:-
CSV data set config to have incremental values and response file name
HTTP request will use ${ID}
Save response to a file will use ${Response_File_Name}
Hope this will help.
I would do this by command line, using a while loop with a curl to the URL, storing the body result on the standard output to a file. It would look something like this:
for i in {1..600000}; do curl "http://google.com/getdata/?id=$i" > body-result-id-$i; done
I couldn't test the line above because I don't have any access to a console right now, but I think it should work.
In Burp you can do this using the Intruder tool. First, capture a sample request in Burp. If you're unsure how to do this, please consult the getting started documentation.
Then right-click the request and selected "Send to Intruder".
In the Positions tab within Intruder, first click "Clear" then select the section you want to vary, and click "Add"
In the Payloads tab select the Payload type as "Numbers" and configure the range.
Click "Start attack"
For more information, consult the documentation.
One Another solution is that you can use Counter in jmeter. That you can find from below path
Thread Group > configElement > Counter.
Configure the Counter as per your need.
Give the Reference Name i for counter.
Use the variable in your request
For more information.

How to differenciate store token in .csv jmeter

Need help.
Need to log in multiple users, so, I'm using CSV Data Set Config. Received dynamic authCode I'm storing in another .csv file, and as the result finaly I'm receiving token, which I also store in .csv.
While posting HTTP request I'm passing token with user data from .csv, How can I differentiate tokens, to post 1000 of request using 4 users only?
Short Answer: JMeter automatically does it for you. you no need to save authCode & token in the CSV files.
Long Answer:
Save the authCode using Regular Expression Extractor. name the variable as authCode.
Replace with ${authCode} wherever authCode value is sent in subsequent requests.
Capture the token value using Regular Expression Extractor and store the value in a variable token
Replace with ${token} wherever token value is sent in subsequent requests.
you no need to worry about the thread/vuser, to associate authCode, token and the corresponding thread. JMeter handles it for you by storing those authCode, token values for each thread and maintains the state.
For more specific answer, please share your Test Plan and mention what exactly you want to achieve.

JMeter - Using cookie field as variable

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.

Resources