Skip to content

Commit 1355890

Browse files
authored
replace partition with split in BasicAuthentication (#8790)
* replace partition with split in BasicAuthentication * test if basic auth without provided password fails
1 parent 1fbe16a commit 1355890

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

rest_framework/authentication.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ def authenticate(self, request):
7878
auth_decoded = base64.b64decode(auth[1]).decode('utf-8')
7979
except UnicodeDecodeError:
8080
auth_decoded = base64.b64decode(auth[1]).decode('latin-1')
81-
auth_parts = auth_decoded.partition(':')
82-
except (TypeError, UnicodeDecodeError, binascii.Error):
81+
82+
userid, password = auth_decoded.split(':', 1)
83+
except (TypeError, ValueError, UnicodeDecodeError, binascii.Error):
8384
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
8485
raise exceptions.AuthenticationFailed(msg)
8586

86-
userid, password = auth_parts[0], auth_parts[2]
8787
return self.authenticate_credentials(userid, password, request)
8888

8989
def authenticate_credentials(self, userid, password, request=None):

tests/authentication/test_authentication.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,22 @@ def test_post_json_passing_basic_auth(self):
120120
)
121121
assert response.status_code == status.HTTP_200_OK
122122

123+
def test_post_json_without_password_failing_basic_auth(self):
124+
"""Ensure POSTing json without password (even if password is empty string) returns 401"""
125+
self.user.set_password("")
126+
credentials = ('%s' % (self.username))
127+
base64_credentials = base64.b64encode(
128+
credentials.encode(HTTP_HEADER_ENCODING)
129+
).decode(HTTP_HEADER_ENCODING)
130+
auth = 'Basic %s' % base64_credentials
131+
response = self.csrf_client.post(
132+
'/basic/',
133+
{'example': 'example'},
134+
format='json',
135+
HTTP_AUTHORIZATION=auth
136+
)
137+
assert response.status_code == status.HTTP_401_UNAUTHORIZED
138+
123139
def test_regression_handle_bad_base64_basic_auth_header(self):
124140
"""Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly"""
125141
# regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate'

0 commit comments

Comments
 (0)