How do I pass authentication bearer tokens to HTTP methods in django.test.Client?
Asked Answered
T

3

12

I am writing tests for endpoints which requires bearer token authentication, but I am getting errors trying to pass authentication errors to HTTP methods like client.post(url,data,**auth_header)

I have tried using both client.login(username=username,password=pass) and client.force_login(user=Users.objects.get(username='admin')) then client.post(url,data)

I have also tried: client.post(url,data,**{'HTTP_AUTHORIZATION': 'Bearer {}'.format(token)}),client.post(url,data,HTTP_AUTHORIZATION='Bearer {}'.format(token)) which both outputs stacktraces

I also tried using AUTHORIZATION, Authorization as keys instead but I would get the permissions error that the endpoint sends if you don't authenticate.

from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
login = client.post('/api/users/login/',{'username':username,'password': password})
bearer = {'HTTP_AUTHORIZATION':'Bearer {}'.format(login.json()['access'])}
response = client.post(url, {'key':'value'}, **bearer)

I am expecting a json response from response var and a status_code of 200 instead I am either getting stack traces or the error returned from the endpoint if you aren't authenticated.

Torrell answered 17/1, 2019 at 18:55 Comment(5)
can you try setting the token explicity? client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token) reference: #50679109Trifacial
I am not rest_framework.test.APIClient, but I just tried using it with client.credentials and I am still getting a stack trace. I even tried using json.dumps() on data too to make sure that wasn't the problem.Torrell
Does the response give what type of auth the endpoint is expecting? It can be gathered from value of the WWW-Authenticate header when the server responds with a 401 status code.Trifacial
It doesn't. This is a endpoint I wrote, which I am now trying to write tests for. In the endpoint I just check to see if the requested user is a super user, if they aren't I send back an 401 status code with the message body that they don't have the correct permissions.Torrell
Could it be that you're missing format=json as a parameter to client.post?Oratorical
A
3

The following worked for me:

token = 'your_token'
data = {"key": "value"}
       
r = client.post(self.ADD_COUPON_URL, data = data, format = 'json',
                                 **{'HTTP_AUTHORIZATION': f'Bearer {token}'},follow = True)
Admetus answered 2/12, 2021 at 16:37 Comment(0)
T
0

Worked for me:

token = 'Bearer ' + 'xxx.xxx.xxx'
response = tester.delete("/user/logout/", headers={'AUTHORIZATION': token})
Titer answered 10/1, 2023 at 4:29 Comment(0)
H
0
client.credentials(HTTP_AUTHORIZATION='Bearer ' + 'AccessTokenFromJWT')

Ref: https://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

Housekeeper answered 3/4 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.