Testing a site with CSRF token or VIEWSTATE

If your site is using some kind of CSRF token and you do a recording using our session recorder, the token recorded will most likely not be valid for simulated users in the load test. The same is true for ASP.NET sites using a VIEWSTATE.

To fix this, you will need to do a little bit of scripting. The first thing you need to do is to save the body data when requesting the page with the form. By default Load Impact will not save any of the data from the requests, so you will need to specify the number of bytes you want to save. Once you have the body of the response, you can start look for the token. This is easiest to do with simple string matching. If you find the token, you can use it as one of the parameters in the following request, usually a POST.

Example code (This is a theoretical example):

-- Make sure you save enough bytes of the reply to include the form, in this case 100000
local pages = http.request_batch({
    {"GET", "http://mydomain.com/myform.html", response_body_bytes=100000}

-- Get the body of the first page
local body = pages[1]['body']

-- Find the actual value of the token
local token = string.match(body, 'input id="token" value="(.-)"')

-- Make the POST request if a the token was found
if token ~= nil then
    -- Use the token value in the following POST
        {"POST", "http://mydomain.com/post", headers={
            data="token=" .. token .. "&foo=bar"
    log.error("Failed to find token")

Note: You will probably want to check the token variable before using it, or you will risk Lua errors in case the page no longer returns the expected content.

See also:

Feedback and Knowledge Base