Как добавить токен аутентификации в заголовок `APIClient` в` django rest_framework test` - PullRequest
0 голосов
/ 04 июня 2018

Я использую oauth2_provider для моего rest_framework.Я пытаюсь написать тестовый пример для моего API.Я получил токен доступа.Но я не могу аутентифицировать пользователя, используя access token в APIClient Я ищу, чтобы эта команда curl работала с APIClient.

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/

Я пытался

client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})

и

client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)

Вот часть фрагмента

from rest_framework.test import APIClient    
from rest_framework.test import APITestCase
....

class APITest(APITestCase):
    def setUp(self):
        ...
        self.client = APIClient()
        ...
        response = self.client.post('/api/v1/oauth2/token/', post_data)
        self.access_token = response.json()['access_token']

    def test_get_current_user(self):
        client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})

Я получаю ответ

<HttpResponseForbidden status_code=403, "text/html; charset=utf-8">

1 Ответ

0 голосов
/ 04 июня 2018

Поскольку вы используете Authorization: Bearer в curl, вы также должны использовать client.credentials со словом Bearer вместо Token:

client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
...