Skip to content

Instantly share code, notes, and snippets.

@markddavidoff
Created March 22, 2018 23:23
Show Gist options
  • Save markddavidoff/7e442b1ea2a2e68d390e76731c35afe7 to your computer and use it in GitHub Desktop.
Save markddavidoff/7e442b1ea2a2e68d390e76731c35afe7 to your computer and use it in GitHub Desktop.
Fix Django Rest Framework DRF BasicAuthentication request is None eror
from rest_framework.authentication import BasicAuthentication
class CustomBasicAuthentication(BasicAuthentication):
"""
DRF.authentication.BasicAuthentication HTTP Basic authentication against username/password with a minor change
to pass request to django.contrib.auth.authenticate as for some reason DRF doesn't pass request...
"""
def authenticate(self, request):
self._current_request = request
return super(CustomBasicAuthentication, self).authenticate(request)
def authenticate_credentials(self, userid, password):
"""
* Copy pasted and added request to **credentials *
Authenticate the userid and password against username and password.
"""
credentials = {
'request': self._current_request
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise 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