Load testing a Rails app with JMeter and the authenticity_token
I have been slowly learning how to use JMeter to load test the Small Payroll application. One of the problems has been getting around the CSRF protection that Rails puts in with the authenticity_token parameter.
Each form has a hidden form element:
<div style="margin:0;padding:0;display:inline">
<input name="authenticity_token" type="hidden"
value="16iUP1J2tdSKyvHKgYR/I/og6K7NgPPmTHCZ+idQP4k=" />
</div>
The token is also encrypted in the session so that the response to the form has to match. This value changes every time the form is loaded and can’t be set to a known value, otherwise it would be easy to defeat the CSRF protection. This means that JMeter has to figure out the token and put it into the POST.
Googling around, I found some people that said they did it, and a lot of people who couldn’t get it to work, but no solid walkthroughs.
Here’s my solution:

There are three elements. The first is the HTTP request sampler that gets the login page. Under that is a regular expression extractor post processor that gets the authenticity token. The extractor uses a simple regexp to pull out the value parameter and saves it to the LOGIN_AUTH_TOKEN variable. The login is then done by making reference to the variable – ${LOGIN_AUTH_TOKEN}. Make sure you have the Encode? button checked, as the authenticity_token is not always base-64 friendly!
The final step, not pictured, is that you have an HTTP Cookie Manager in your thread group to take care of cookies. You probably already have one, though.
Sean

Works great! Thanks.
August 7th, 2010 at 11:02 amIt has worked for me to.
December 14th, 2010 at 8:46 amThank you.
It worked for me after I changed the regular expression to:
<input\s+name=”authenticity_token”\s+type=”hidden”\s+value=”(.*?)”\s*\/>
(\s+ instead of empty spaces)
January 24th, 2011 at 8:55 pmLogging works great for me, but the session is immediately reseted.
March 20th, 2011 at 12:16 pmI have set a cookie and a cache manager. (Rails 2.3.11 & Devise 1.0.9)
If anybody have an idea ?!
Great!!! This Post helped me a lot and saved my time.
August 9th, 2011 at 10:19 pm[...] This article provides a detailed explanation how to do it. I only used s+ instead of empty spaces to make it work. [...]
September 8th, 2011 at 6:05 pm