Skip to content

Commit e19b21e

Browse files
glarraintomchristie
authored andcommitted
Handle incorrectly padded HTTP basic auth header (#4090)
1 parent a9bbb50 commit e19b21e

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

rest_framework/authentication.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from __future__ import unicode_literals
55

66
import base64
7+
import binascii
78

89
from django.contrib.auth import authenticate, get_user_model
910
from django.middleware.csrf import CsrfViewMiddleware
@@ -77,7 +78,7 @@ def authenticate(self, request):
7778

7879
try:
7980
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
80-
except (TypeError, UnicodeDecodeError):
81+
except (TypeError, UnicodeDecodeError, binascii.Error):
8182
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
8283
raise exceptions.AuthenticationFailed(msg)
8384

tests/test_authentication.py

+8
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,14 @@ def test_post_json_passing_basic_auth(self):
8585
response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
8686
self.assertEqual(response.status_code, status.HTTP_200_OK)
8787

88+
def test_regression_handle_bad_base64_basic_auth_header(self):
89+
"""Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly"""
90+
# regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate'
91+
# https://github.com/tomchristie/django-rest-framework/issues/4089
92+
auth = 'Basic =a='
93+
response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
94+
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
95+
8896
def test_post_form_failing_basic_auth(self):
8997
"""Ensure POSTing form over basic auth without correct credentials fails"""
9098
response = self.csrf_client.post('/basic/', {'example': 'example'})

0 commit comments

Comments
 (0)