CSRF Tokens

Learn how to use CSRF tokens in your test case

Many sites use CSRF tokens to prevent cross-site request forgery. In this case you need to extract those tokens and send them along with subsequent requests.

For further information on content extraction take a look at our reference.

Extract CSRF Token

In your test case definition you can extract the token from a response body like:

{
  "authorization": {
    "csrfToken": "noXuMgKei5pPP4wdv5Kq"
  }
}

with the following option:

session.get("/users/register", {
  tag: "fetch_token",
  extraction: {
    jsonpath: {
      "csrfToken": "authorization.csrfToken"
    }
  }
});

You can then use the csrfToken as a dynamic data source within the same session:

session.post("/users/register", {
  tag: "registration",
  payload: {
    token: session.getVar("csrfToken"),
    username: "Foo",
    password: "bar"
  }
});
Last modified May 16, 2022