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.
client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
reference: #50679109 – Trifacialjson.dumps()
on data too to make sure that wasn't the problem. – TorrellWWW-Authenticate
header when the server responds with a 401 status code. – Trifacialformat=json
as a parameter toclient.post
? – Oratorical