11

I am using Locust (python) to load test on a Django web app. I keep getting a 403 error when I run my script.

Here is the code:

  from locust import HttpLocust, TaskSet

def index(l):
    l.client.get("/")
def login(l):
    l.client.post("/login/", {"username":"an@id.com", "password":"education")
def upload(l):
    l.client.get("/upload-image/")
def home(l):
  l.client.get("/home/")
def settings(l):
 l.client.get("/settings/")
def logout(l):
 l.client.get("/logout/")
class UserBehavior(TaskSet):
    tasks = {index:1, upload:1, home:1, settings:1, logout:1}

    def on_start(self):
        login(self)

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait=5000
    max_wait=9000
Wipqozn
  • 1,282
  • 2
  • 17
  • 30
atkawa7
  • 461
  • 1
  • 6
  • 13
  • A status of 403 means forbidden, so your credentials are wrong. Either the user doesn't exist or you've forgotten to pass CSRF token to your view. – Henrik Andersson Dec 03 '14 at 00:32
  • How do you pass in a crsf token – atkawa7 Dec 03 '14 at 00:32
  • 1
    Just a note, having logout as a task means that Locust will pick that sometimes and then you will have an unauthorized client attempting to interact with your application, and you will get 401/403 errors again. – Zeroth Oct 04 '17 at 16:16

2 Answers2

18

To expand on ZacDelagrange's answer, when you are using https, you must also set the Referer header, so in this example you could do

def on_start(self):
    """ Run on start for every Locust hatched """
    r = self.client.get('')
    self.client.headers['Referer'] = self.client.base_url
    self.client.post('/accounts/login/', 
        {'email': 'email', 'password': 'password',
         'csrfmiddlewaretoken': r.cookies['csrftoken']})
TheAxeR
  • 622
  • 5
  • 5
7

Do a get on your root or login page, grab the csrf token from the response cookie, and post to your login url with the csrftoken. This should add the csrf token to the client's cookies and allow you to browse the page.

def on_start(self):
    """ Run on start for every Locust hatched """
    r = self.client.get('')
    self.client.post('/accounts/login/', 
        {'email': 'email', 'password': 'password',
         'csrfmiddlewaretoken': r.cookies['csrftoken']})
ex-zac-tly
  • 979
  • 1
  • 8
  • 24