Christopher Stephenson
Christopher Stephenson

Reputation: 502

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

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.

Upvotes: 12

Views: 5782

Answers (3)

walawalaboom
walawalaboom

Reputation: 99

client.credentials(HTTP_AUTHORIZATION='Bearer ' + 'AccessTokenFromJWT')

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

Upvotes: 0

Athif Saheer
Athif Saheer

Reputation: 4647

Worked for me:

token = 'Bearer ' + 'xxx.xxx.xxx'
response = tester.delete("/user/logout/", headers={'AUTHORIZATION': token})

Upvotes: 0

Allex Radu
Allex Radu

Reputation: 1530

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)

Upvotes: 3

Related Questions