Django自定义后端导致登录错误

问题描述 投票:0回答:1

写了自定义django后端,点击signin按钮后调用authenticate并失败并显示错误:

'dict' object has no attribute 'backend'

我将字符串推送到身份验证后端

AUTHENTICATION_BACKENDS = [
    'app_auth.auth_backend.AuthBackend'
]

可能出什么问题?

堆栈跟踪:

Internal Server Error: /sign-in/
Traceback (most recent call last):
  File "C:\django-proj\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\django-proj\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\django-proj\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\django-proj\app_auth\views.py", line 12, in sign_in
    user = authenticate(request, username=username, password=password)
  File "C:\django-proj\env\lib\site-packages\django\contrib\auth\__init__.py", line 73, in authenticate
    user = backend.authenticate(request, **credentials)
  File "C:\django-proj\app_auth\auth_backend.py", line 24, in authenticate
    user.backend = 'app_auth.auth_backend.AuthBackend'
AttributeError: 'dict' object has no attribute 'backend'
[21/Feb/2019 22:53:20] "POST /sign-in/ HTTP/1.1" 500 78995
[21/Feb/2019 23:15:25] "GET /sign-in/ HTTP/1.1" 200 1274

验证功能

from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
from services.db.users import get_user, get_user_by_id

class AuthBackend():
    def authenticate(self, request, username=None, password=None):
        user = get_user(username=username)
        return user

    def get_user(self, user_id):
        return get_user_by_id(id=user_id)

get_userget_user_by_id返回存根数据

user = {
    'name': 'user-name',
    'backend': 'app_auth.auth_backend.AuthBackend'
}


def get_user(username):
    return user


def get_user_by_id(id):
    return user
python django
1个回答
0
投票

该错误表示在第2行的身份验证中,您正在设置user.backend = 'app_auth.auth_backend.AuthBackend',并且该dict没有该属性。

您正在错误地访问该字段。如果user是一个字典,并且你想设置一个名为backend的属性的值,那么你的第24行应该是:

user['backend'] = 'app_auth.auth_backend.AuthBackend'
© www.soinside.com 2019 - 2024. All rights reserved.