Skip to content

Instantly share code, notes, and snippets.

@markddavidoff
Last active December 13, 2018 20:20
Show Gist options
  • Save markddavidoff/4156b8072e587b77e639269fbfac3b0f to your computer and use it in GitHub Desktop.
Save markddavidoff/4156b8072e587b77e639269fbfac3b0f to your computer and use it in GitHub Desktop.
Django Rest Framework BasicAuthentication infinite loop workaround
from rest_framework.request import Request as DRFRequest
class CustomBasicAuthentication(BasicAuthentication):
"""
NOTE: This is not the default method used to authenticate, this is to be used with DRF authentication_classes for
any views that need HTTP Basic Auth
DRF.authentication.BasicAuthentication HTTP Basic authentication against username/password with a minor change
to show messages returned in response_context
"""
def authenticate_credentials(self, userid, password, request=None):
"""
Copy pasted and added response_context
Authenticate the userid and password against username and password.
"""
response_context = {}
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password,
'response_context': response_context
}
if request and isinstance(request, DRFRequest):
# DRF wraps request, so pass the original internal one
# to prevent an infinite loop where DRF's Request.user calls authenticate()
request = request._request
user = authenticate(request=request, **credentials)
if user is None:
if 'error' in response_context:
drf_exceptions.AuthenticationFailed(_(response_context['error']))
raise drf_exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise drf_exceptions.AuthenticationFailed(_('User inactive or deleted.'))
return user, None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment