I am trying to implementing django custom authentication with custom user model using JWT. I have written CustomUser model and CustomAuthBackend and configured for using JWT.
Below is the snapshot of project's settings.py :
AUTH_USER_MODEL = 'users.CustomUser'
AUTHENTICATION_BACKENDS = ('project.users.backends.CustomAuthBackend', )
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_ALLOW_REFRESH': True,
}
REST_USE_JWT = True
LOGGING = {
'version': 1,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
Before using custom authentication, I created 2 users and after implementing custom authentication trying to login (http://127.0.0.1:8000/admin/) using one of those credentials but getting "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." message.
Trying to debug the custom authentication but even prints are not coming on console. Also tried using logging module but its also not working. So I doubt that my custom authentication function def authenticate(self, request, email, password) itself might not being called.
Here is the code for that:
from project.users.models import CustomUser
from rest_framework import authentication
import logging
class CustomAuthBackend(object):
def authenticate(self, request, email, password):
# Get an instance of a logger
print ("Inside CustomAuthBackEnd")
logger = logging.getLogger(__name__)
logger.info("Authenticating user........")
print >> sys.stderr, "debug the error"
try:
user = CustomUser.objects.get(email=email)
print("__name__: ", __name__)
print("email: ", email)
print("user: ", user)
if user.check_password(password):
return user
else:
return None
except CustomUser.DoesNotExist:
logger.error("user with login %s does not exists " % login)
return None
except Exception as e:
logger.error(repr(e))
return None
def get_user(self, user_id):
logger.info("Getting user........")
try:
user = CustomUser.objects.get(pk=user_id)
#user = CustomUser.objects.get(sys_id=user_id)
return user
#if user.is_active:
# return user
#return None
except CustomUser.DoesNotExist:
logger.error("user with %(user_id)d not found")
return None;
Can someone please tell whether def authenticate(self, request, email, password) function is called or not or how can I debug it ?
Version used: django=2.0.1 djangorestframework==3.7.7 Python 3.4.3
print >> sys.stderr, "debug the error"isn't valid use ofprint- you should get an exception about not being able to apply the>>operator between a function andsys.stderr- so I'd expect you'd get an exception fairly quickly if it was running fine. - Jon Clements♦