Django授权后端+始终返回'user.is_authenitcated'false

时间:2018-08-24 13:47:15

标签: python django django-rest-framework

我正在使用授权后端,以便使用带有用户名和密码(我们自己的加密技术)的自己的数据库。

现在,当我运行服务器时,它会给我登录按钮。使用它我可以成功登录。作为回报,我可以吸引用户。下面是该代码。

from django.contrib.auth.models import User
from workforce.models import GlobalUsers
from rest_framework.response import Response
from workforce.globalapiviews import hash_password

class EmailAuthBackend(object):

    def authenticate(self, request, username=None, password=None):
        try:
            hashedpassword = hash_password(password)
            user = GlobalUsers.objects.get(username=username, password=hashedpassword)
            print(hashedpassword)
            if user:
                return user
            else:
                return None
        except GlobalUsers.DoesNotExist:
            return Response(status=status.HTTP_204_NO_CONTENT)

    def get_user(self, wf_user_id):
        try:
            print(wf_user_id)
            return GlobalUsers.objects.get(pk=wf_user_id)
        except GlobalUsers.DoesNotExist:
            print(wf_user_id)
            return None

使用HTML时,即使成功登录也始终显示“ LOGIN”按钮。

观察到,user.is_authenticated始终返回false。

有人可以建议我做错了吗

谢谢。

2 个答案:

答案 0 :(得分:0)

您的代码

    def authenticate(self, request, username=None, password=None):
        try:
            hashedpassword = hash_password(password)
            user = GlobalUsers.objects.get(username=username, password=hashedpassword)
            print(hashedpassword)
            if user:
                return user
            else:
                return None
        except GlobalUsers.DoesNotExist:
            return Response(status=status.HTTP_200_OK)

GlobalUsers.objects.get()会在找不到用户时引发异常(它永远不会返回None)。在这种情况下,您将返回一个Response(200_OK)

autenticate()应该引发异常,如果您想使身份验证失败,或者如果要传递到下一个后端,则返回None。

official documentation

答案 1 :(得分:0)

如果您需要锁定Browsable API以便在不登录的情况下进行访问,则只需将此配置添加到设置中。py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

然后提供一种简便的登录方法,您可以在使用浏览器时将以下内容添加到相同的设置中。py:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}