title: What's the proper way to test token-based auth using APIRequestFactory?
body: <p>The query to my endpoint works fine (as long as I pass it a valid token), it returns the json representation of my response data.</p>
  
  <p>The code in the service api that calls my endpoint, passing an auth token in the header:</p>
  
  <pre><code>headers = {'content-type': 'application/json',
             'Authorization': 'Token {}'.format(myToken)}
  url = 'http://localhost:8000/my_endpoint/'
  r = session.get(url=url, params=params, headers=headers)
  </code></pre>
  
  <p>In views.py, I have a method decorator that wraps the dispatch method on the view (viewsets.ReadOnlyModelViewSet):</p>
  
  <pre><code>def login_required(f):
      def check_login_and_call(request, *args, **kwargs):
          authentication = request.META.get('HTTP_AUTHORIZATION', b'')
          if isinstance(authentication, str):
              authentication = authentication.encode(HTTP_HEADER_ENCODING)
          key = authentication.split()
          if not key or len(key) != 2:
              raise PermissionDenied('Authentication failed.')
          user, token = authenticate_credentials(key[1])
          return f(request, *args, **kwargs)
      return check_login_and_call
  </code></pre>
  
  <p>I'm trying to write a test to authenticate the request using a token:</p>
  
  <pre><code>from rest_framework.authtoken.models import Token
  from rest_framework.test import APIRequestFactory
  from rest_framework.test import APITestCase
  from rest_framework.test import force_authenticate
  
  class EndpointViewTest(APITestCase):
      def setUp(self):
          self.factory = APIRequestFactory()
          self.user = User.objects.create_user(
              username='user@foo.com', email='user@foo.com', password='top_secret')
          self.token = Token.objects.create(user=self.user)
          self.token.save()
  
      def test_token_auth(self):
          request = self.factory.get('/my_endpoint')
          force_authenticate(request, token=self.token.key)
          view = views.EndpointViewSet.as_view({'get': 'list'})
          response = view(request)
          self.assertEqual(response.status_code, 200)
          json_response = json.loads(response.render().content)['results']
  </code></pre>
  
  <p>For some reason, I cannot get the request to properly pass the token for this test. Using force_authenticate doesn't seem to change the header that I'm using for validating the token. The current output is raising "PermissionDenied: Authentication failed." because the token isn't being set on the request.</p>
  
  <p>Is there a proper way to set this in the request header in my test or to refactor the way I'm using it in the first place?</p>