Test guides

Login with CSRF Token

Many websites today implement CSRF tokens as a part of their login process. LoadForge can read these tokens and use them in your tests.

The way LoadForge achieves this is by requesting the login page and scanning the content for the given input field holding the CSRF token. The best way to illustrate this is with a test example.

The below example posts to a login page when it starts, then requests /hello and /world normally. However, it also specifically handles getting a CSRF token for logging in with (in this example) Laravel.

About CSRF

CSRF is designed to stop cross-site scripting against your site, and involves having a temporary token on each page that is submitted with every post. You'll know you've hit this issue if you receive an HTTP 419 error.

The below example can also be used for many other frameworks, or altered to suit them.

Code

from locust import HttpUser, task, between
from pyquery import PyQuery


class QuickstartUser(HttpUser):
    # Wait between 5 and 9 seconds per request per user
    wait_time = between(5, 9)


    # on_start is run when a user is first spawned
    def on_start(self):
        response = self.client.get("/login")


        pq = PyQuery(response.content)


        # find an input with name="_token"
        elements = pq("input[name=_token]")
        for token in elements:
          csrftoken = token.value


        # debug example
        #print("my token is:", csrftoken)


        # post using the token
        self.client.post("/login", {
            "email": "user@domain.com",
            "password": "secr3t",
            "_token" : csrftoken
        })


    @task(1)
    def index_page(self):
        # Request /dashboard on your Host
        self.client.get("/dashboard")
Previous
Submitting forms