replace partition with split in BasicAuthentication (#8790)

* replace partition with split in BasicAuthentication

* test if basic auth without provided password fails
This commit is contained in:
Jakub Bodek 2022-12-08 04:52:35 +01:00 committed by GitHub
parent 1fbe16a8d2
commit 1355890f9f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 3 deletions

View File

@ -78,12 +78,12 @@ class BasicAuthentication(BaseAuthentication):
auth_decoded = base64.b64decode(auth[1]).decode('utf-8') auth_decoded = base64.b64decode(auth[1]).decode('utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
auth_decoded = base64.b64decode(auth[1]).decode('latin-1') auth_decoded = base64.b64decode(auth[1]).decode('latin-1')
auth_parts = auth_decoded.partition(':')
except (TypeError, UnicodeDecodeError, binascii.Error): userid, password = auth_decoded.split(':', 1)
except (TypeError, ValueError, UnicodeDecodeError, binascii.Error):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.') msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg) raise exceptions.AuthenticationFailed(msg)
userid, password = auth_parts[0], auth_parts[2]
return self.authenticate_credentials(userid, password, request) return self.authenticate_credentials(userid, password, request)
def authenticate_credentials(self, userid, password, request=None): def authenticate_credentials(self, userid, password, request=None):

View File

@ -120,6 +120,22 @@ class BasicAuthTests(TestCase):
) )
assert response.status_code == status.HTTP_200_OK assert response.status_code == status.HTTP_200_OK
def test_post_json_without_password_failing_basic_auth(self):
"""Ensure POSTing json without password (even if password is empty string) returns 401"""
self.user.set_password("")
credentials = ('%s' % (self.username))
base64_credentials = base64.b64encode(
credentials.encode(HTTP_HEADER_ENCODING)
).decode(HTTP_HEADER_ENCODING)
auth = 'Basic %s' % base64_credentials
response = self.csrf_client.post(
'/basic/',
{'example': 'example'},
format='json',
HTTP_AUTHORIZATION=auth
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_regression_handle_bad_base64_basic_auth_header(self): def test_regression_handle_bad_base64_basic_auth_header(self):
"""Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly""" """Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly"""
# regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate' # regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate'