Locust: How to perform basic authentication?

Created on 31 May 2018  路  4Comments  路  Source: locustio/locust

Description of issue / feature request

Hi guys! Tried to find the answer for my question among the other issues but couldn't find. I have basic auth in my web application. Could someone send me the example of locustfile.py, how to correctly perform the auth in this case?

2018-05-31 13_14_11-mozilla firefox

Tried the following code, but it doesn't work. I'm getting the "HTTPError('401 Client Error: Unauthorized for url"

My locustfile.py

from locust import HttpLocust, TaskSet, task
class Tests(TaskSet):

    def on_start(self):
        """ on_start is called when a Locust start before any task is scheduled """
        self.login()

    def login(self):
        self.client.post("myURL", {"username":"myusername", "password":"mypassword"})

    @task(1)
    def profile(self):
        self.client.get("/api/test")

class WebsiteUser(HttpLocust):
    host = "myURL"
    task_set = Tests
    min_wait = 5000
    max_wait = 9000
  • OS: Windows 10
  • Python version: 3.6.3
  • Locust version: 0.81

Most helpful comment

like this:
self.client.get(myURL, auth=(myusername, mypassword))

http://docs.python-requests.org/en/master/user/authentication/#basic-authentication

All 4 comments

like this:
self.client.get(myURL, auth=(myusername, mypassword))

http://docs.python-requests.org/en/master/user/authentication/#basic-authentication

@cgoldberg
Thank you!
One more question, how to get the auth token from headers?

For now, I have such function:

def login(self):
    response = self.client.request(method="GET", url = "/myurl/api", auth=("Administrator", "superuser"))

I can print the request headers:
print(response.request.headers)

Here's what I get:
{'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Basic QWRtaW5pc3RyYXRvcjpzdXBlcnVzZXI='}

And I need to get the following in JSONformat:
'Authorization': 'Basic QWRtaW5pc3RyYXRvcjpzdXBlcnVzZXI='

Thank you in advance!

closing this since original issue was solved.

it's a dict.. so use the key:
response.request.headers['Authorization']

Was this page helpful?
0 / 5 - 0 ratings