From 7ae71deb845e0cbe020a4054ba46ab4bed44d6e3 Mon Sep 17 00:00:00 2001 From: Osvaldo Santana Neto Date: Wed, 3 Jun 2015 14:55:34 -0300 Subject: [PATCH] Handle invalid characters in headers --- rest_framework/authentication.py | 8 +++++++- tests/test_authentication.py | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 8b5c20090..598c72788 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -170,7 +170,13 @@ class TokenAuthentication(BaseAuthentication): msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) - return self.authenticate_credentials(auth[1]) + try: + token = auth[1].decode() + except UnicodeError: + msg = _('Invalid token header. Token string should not contain invalid characters.') + raise exceptions.AuthenticationFailed(msg) + + return self.authenticate_credentials(token) def authenticate_credentials(self, key): try: diff --git a/tests/test_authentication.py b/tests/test_authentication.py index 91e49f9d8..0307d9989 100644 --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -1,3 +1,5 @@ +# coding: utf-8 + from __future__ import unicode_literals from django.conf.urls import patterns, url, include from django.contrib.auth.models import User @@ -162,6 +164,12 @@ class TokenAuthTests(TestCase): response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, status.HTTP_200_OK) + def test_fail_post_form_passing_invalid_token_auth(self): + # add an 'invalid' unicode character + auth = 'Token ' + self.key + "ΒΈ" + response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + def test_post_json_passing_token_auth(self): """Ensure POSTing form over token auth with correct credentials passes and does not require CSRF""" auth = "Token " + self.key