Locust Directory

Getting Auth Token

Send a login request to get an authorization token for the rest of your test

Overview

Below is a partial test (just the on_start section) that shows how to set an authorization (or really any) header based on response content at launch with your load test.

Naturally, you would not do all of these. They are 3 examples of getting a Bearer token in different ways.

Code

from locust import HttpUser, TaskSet, task
import requests

class UserBehavior(TaskSet):
  def on_start(self):
  	  # Send login request
      response = requests.post("http://mysite.com/login", {"username": "user", "password": "pass"})
      
      # set "token" from response header
      self.client.headers.update({'Authorization': response.headers.get('token')})

      # OR set "token" from response cookies
      self.client.cookies.set('Authorization', response.cookies.get('token'))
      
      # OR set "token" from response body
      self.client.headers.update({'Authorization': str(response.content.decode().find('token'))})      


This guide is part of the LoadForge Directory, an index of locustfile's for use with LoadForge website and API load tests. We also provide a wizard to generate tests, and onboarding assistance for clients. Contact us should you have any questions.

LoadForge provides load testing and stress tests for websites, APIs and servers. It uses your cloud account to rapidly scale large numbers of simulated users to load test your website, store, API, or application for cheap - just cents per test!

For more help on Tests please see our official documentation. Logged in users can also use our wizard to generate a locustfile, or you can record your browser steps.

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