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.

  • 1
    can you try setting the token explicity? `client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)` reference: https://stackoverflow.com/questions/50678609/how-to-add-authentication-token-in-header-of-apiclient-in-django-rest-framewo – quirkystack Jan 17 '19 at 19:17
  • 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. – Christopher Stephenson Jan 17 '19 at 19:28
  • 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. – quirkystack Jan 17 '19 at 20:09
  • 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. – Christopher Stephenson Jan 17 '19 at 20:25
  • Could it be that you're missing `format=json` as a parameter to `client.post`? – ezdazuzena Feb 10 '20 at 11:33

2 Answers2

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)
Athif Saheer
  • 4,539
  • 3
  • 9
  • 14
Allex Radu
  • 1,257
  • 13
  • 24
0

Worked for me:

token = 'Bearer ' + 'xxx.xxx.xxx'
response = tester.delete("/user/logout/", headers={'AUTHORIZATION': token})
Athif Saheer
  • 4,539
  • 3
  • 9
  • 14