Django自定义身份验证无法正常工作

时间:2018-02-25 13:17:32

标签: django python-3.x

我正在尝试使用JWT使用自定义用户模型实现django自定义身份验证。我编写了CustomUser模型和CustomAuthBackend并配置为使用JWT。

以下是项目的 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,
               },
           },
        }

在使用自定义身份验证之前,我创建了2个用户,并在实施自定义身份验证后尝试使用其中一个凭据登录(http://127.0.0.1:8000/admin/)但获取“请为员工帐户输入正确的电子邮件和密码。”字段可能区分大小写。“消息。

尝试调试自定义身份验证,但即使打印也不会出现在控制台上。也试过使用日志模块,但它也无法正常工作。所以我怀疑我的自定义身份验证功能def authenticate(self,request,email,password)本身可能没有被调用。

以下是代码:

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;

有人可以告诉我们是否调用了def身份验证(自我,请求,电子邮件,密码)功能,或者我该如何调试它?

使用的版本: 的django = 2.0.1 djangorestframework == 3.7.7 Python 3.4.3

1 个答案:

答案 0 :(得分:0)

尝试了很多东西,但有效的是Django Shell。

运行" python3 manage.py shell"你将进入shell提示。

现在因为我已实施自定义身份验证,所以如果我导入 来自django.contrib.auth导入身份验证并从shell提示符调用authenticate函数,然后应调用我的自定义身份验证函数(如果所有内容都已正确实现和配置)。我试过一样,打印开始了。

之前发生的事情是,身份验证功能本身没有被调用,因此打印件没有出现。

我能弄明白的原因是我实现了它 def authenticate(自我,请求,电子邮件,密码) 但如果我把它(来自shell)称为 authenticate(用户名=" root",密码="密码123")它不会被调用但是如果我打电话为authenticate(email =" root@gmail.com",密码="密码123")然后它将被调用,内部Django框架可能会以第一种方式调用它。

我是python,django的新手,所以我不知道里面发生了什么,但看起来像参数的名字,而调用函数应该与函数定义中的参数名称相匹配。