By Hamid Al-qiari - Performance Test Lead
Handling CSRF Tokens in JMeter
What is CSRF Token
A CSRF Token is a secret, unique and unpredictable value a server-side application generates in order to protect CSRF vulnerable resources.
The tokens are generated and submitted by the server-side application in a subsequent HTTP request made by the client.
After the request is made, the server side application compares the two tokens found in the user session and in the request. If the token is missing or does not match the value within the user session, the request is rejected, the user session terminated and the event logged as a potential CSRF attack.
When do you need CSRF token with JMeter
We need a CSRF token during the load test. Actually, the CSRF token is generated at run time and can be used only once, so if you use its hard-coded value in your script then your run will fail, because that is a used token and is no longer valid for use.
How to handle CSRF token with JMeter
Login to a website using JMeter is a very important aspect of this load testing tool ,sometimes it is not easy if the website is CSRF protected .
To do this, first we need to record this login activity to get the number of calls which are necessary to log into an application.
I am going to show you how to simulate this on the Firehouse Front Desk web application .
1-Add the test script recorder on jmeter test plan
2-Configure the proxy on Firefox browser
3-Login to the app on the browser and check the recorded requests on JMeter
If we try to login using the same token ,login fails because we used the same token that was invalid this time .We need to use a valid token while passing the credentials .
To retrieve the token we run the login page twice .
First time using the “GET” method to retrieve a token from the body using a Regular Expression Extractor .
Regular expression extractor handles this csrfToken and its value because each time this value is changed.
In Regular expression extractor we have to define a certain field:
Reference Name: token
Regular expression: name=”_token” value=”(.+?)”
Template: $1$
Match no: 1
Second Time will use this extracted token with the Login “POST” method with the credentials.
Now , the important part is to add a cookie manager .
Run your JMeter script :
Now I am able to login successfully with an extracted CSRF token .
Good Job!
ReplyDelete