Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Token to headers request in TEST mode DRF

how is possible to add 'Authorization': 'Token' to TEST request in Django/DRF?

If i use simple requests.get(url, headers={'Authorization': 'Token'} all work perfect but how to do such request in TestCase?

like image 985
Beliaf Avatar asked Nov 16 '17 14:11

Beliaf


People also ask

How do I add auth token in header?

The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.

How do you get bearer tokens in Django?

You can get the token from the request. auth attribute. It returns a DRF Token instance. If you want only the key then you can access it with the request.


1 Answers

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

from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
like image 145
origamic Avatar answered Nov 02 '22 19:11

origamic