2

I am checking a request header for a valid token in my custom middleware.

class CustomTokenAuthentication(object):

def process_request(self, request):

    access_token = request.META.get('HTTP_TOKEN', '')
    if AccessToken.objects.filter(token=access_token).exists():
        return None
    else:
        # return None
        res =  HttpResponse("Invalid token", status=401)
        res["WWW-Authenticate"] = "Invalid Token"
        return res

seems to work fine, but im stuck writing a test by setting a header HTTP_TOKEN with a valid token value and geting a 200 response.

my sample testcode

def test_invalid_token_present(self):
    resp = self.client.get(reverse('productlist'), **{'HTTP_TOKEN':'8742627sdfsdfsf4e3423dsd23'})
    self.assertEqual(resp.status_code,200)

seems to fail always.

5
  • try HTTP-TOKEN when sending the request. Commented Jul 30, 2016 at 13:28
  • sorry, try just TOKEN instead Commented Jul 30, 2016 at 13:33
  • still fails @EagerNoob Commented Jul 30, 2016 at 13:38
  • 1
    can you print the contents of request.META.keys() and check. Commented Jul 30, 2016 at 13:41
  • I meant try the header TOKEN in the request. I actually went ahead and tried it. If it doesn't work, then we'll have to look at the contents of request.META. Commented Jul 30, 2016 at 14:02

1 Answer 1

5

Django renames CUSTOM-HEADER to HTTP_CUSTOM_HEADER. When you send it HTTP_TOKEN it will get renamed to HTTP_HTTP_TOKEN in the request.META dict. A simple way to check what headers you are getting is to either print request.META and check the console or insert a pdb breakpoint just before the check and examin the request.META dict - link to relevant Django doc. So try:

    resp = self.client.get(reverse('productlist'),
                           **{'TOKEN':'8742627sdfsdfsf4e3423dsd23'})

I advise you to limit your line lengths, so that people don't have to scroll horizontally to read your code. PEP-8 prescribes an 80 character limit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.