【问题标题】:Django Authorization Backends + always returning 'user.is_authenitcated' falseDjango授权后端+总是返回'user.is_authenitcated' false
【发布时间】:2019-01-31 00:26:21
【问题描述】:

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

现在,当我运行服务器时,它给了我登录按钮。使用它我成功登录。作为回报,我能够获得用户。下面是它的代码。

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 时,即使在成功登录的情况下也总是显示“登录”按钮。

观察到,user.is_authenticated 总是返回 false。

谁能告诉我我做错了什么。

提前致谢。

【问题讨论】:

  • 向我们展示您的代码
  • @gogaz 添加了代码。
  • 你的目标是什么?您想锁定特定的 ViewSet 还是只想在 Browsable API 上登录?
  • 也许我错了,但也不应该打电话给login() ??
  • authenticate() 不应返回响应

标签: python django django-rest-framework


【解决方案1】:

你的代码

    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

【讨论】:

  • 我已经编辑和验证了代码,即使它是一样的。而且我正在获取用户,因此它不会属于不存在的情况。
  • 我没有看到任何代码更改。您仍在异常处理中返回响应,您必须在那里返回 None 或引发异常
【解决方案2】:

如果您需要锁定 Browsable API 以在不登录的情况下访问,您只需将此配置添加到您的 settings.py 中

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

然后,为了在使用浏览器时提供一种简单的登录方式,您可以将以下内容添加到相同的 settings.py 中:

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

【讨论】:

  • 感谢您的回答,我已经尝试过了。还是同样的问题。
  • 几分钟前我在这个存储库上实现了它并且运行良好....
猜你喜欢
  • 2018-01-07
  • 2021-04-11
  • 2014-07-03
  • 2019-07-20
  • 2019-08-29
  • 2014-09-06
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多