LF BLOG // Laravel 419 Errors During Testing - CSRF Tokens

UPDATE 2021/09/06 - We recommend reading our brand new guide for dealing with 419 errors! Login with CSRF Token

Laravel automatically checks for a CSRF token when you submit data (by default). 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.

In LoadForge you will see that show up as the following error if it's not handled:

HTTPError('419 Client Error: for url: https://loadforge.com/login') 

You have two options when handling a CSRF token during load testing:

  • Disable CSRF protection for the load test. With Laravel you can do this by temporarily removing the VerifyCsrfToken middleware.
  • or, GET the token from the page before your POST it

For option 2, Laravel conveniently supports an HTTP cookie called XSRF-TOKEN with requests, that can then be sent as the HTTP header "X-XSRF-TOKEN" on the next request. Below is a snippet of achieving this to be used with a full locustfile:

def post_answer(self):
    response = self.client.get("/login")
    csrftoken = response.cookies['XSRF-TOKEN']

                     {"username": "my_user", "password": "my_password"}, 
                     headers={"X-XSRF-TOKEN": csrftoken})

You can see we send a GET request to /login to get the XSRF-TOKEN cookie, then we send that as a header in our POST to /login.

There is a full locustfile available in the directory for CSRF load testing.

Ready to run that test?
Start your first test within minutes.