【问题标题】:Custom Authentication returning NULL everytime in django自定义身份验证每次在 Django 中返回 NULL
【发布时间】:2021-12-21 23:07:08
【问题描述】:

我是 django 的初学者,我想使用自定义用户模型构建身份验证。 我问过问题Here。有人建议我继承用户模型。

我创建了自定义用户模型。由于所有密码都是使用 bcrypt 函数存储的,所以我创建了自己的自定义身份验证。现在每次我登录时,即使我的密码是正确的,我也会得到无。我想知道我错过了什么?

models.py


class AdminUserManager(BaseUserManager):
    def create_user(self, username, password):
        if username is None or password is None:
            raise ValueError("Username and Password is Required")
        else:
            user = self.model(
                username = username,
                password = str(bcrypt.hashpw(password.encode('utf8'),bcrypt.gensalt()),'utf-8')
            )
            user.save(using=self.db)
            return user



class AdminUsers(AbstractBaseUser):
    username=models.CharField(max_length=50,unique=True)
    firstname=models.CharField(max_length=50)
    department=models.CharField(max_length=50)
    mail=models.CharField(max_length=50)
    id=models.IntegerField(primary_key=True)
    password=models.CharField(max_length=200)
    # some more field
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['mail']

    objects = AdminUserManager()
    class Meta:
        db_table="admin_users"

    def __str__(self):
        return self.username

后端.py

from .models import AdminUsers
import bcrypt

class CustomAuthentication(object):
    def authenticate(self,username,password):
        if username is not None and password is not None:
            user = AdminUsers.objects.get(username=username)
            hashed_password = user.password
            is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
            if is_check == True:
                return user
            else:
                return None
        else:
            return None
    
    def get_user(self,id):
        user = AdminUsers.objects.get(id=id)
        if user is not None:
            return user
        else:
            return None
        

views.py

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username is not None and password is not None:
            is_check = authenticate(username=username,password=password)
            # user=AdminUsers.objects.get(username=username)
            # print(user.username,user.password)
            # hashed_password = user.password
            # is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
            print(is_check)
            if is_check==True:
                return render(request,'Layouts/nav-side-bar.html',context={"User":is_check})
            else:
                return render(request,'AdminUsers/login.html')
    return render(request,'AdminUsers/login.html')

我在设置中添加了AUTHENTICATION_BACKENDS 和 AUTH_USER_MODEL 。

*** 编辑 1 ***

为了检查我的 CustomAuthentication 是否正常工作,在身份验证功能中,我注释了一些部分并返回用户而不检查密码。我仍然没有。 据我了解,我的自定义身份验证没有用于身份验证。

def authenticate(self,username,password):
        if username is not None and password is not None:
            user = AdminUsers.objects.get(username=username)
            return user
            # hashed_password = user.password
            # is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
            # if is_check == True:
            #     return user
            # else:
            #     return None
        else:
            return None

【问题讨论】:

    标签: python django


    【解决方案1】:

    我在创建 CustomAuthentication 时犯了错误。 在创建 CustomAuthentication 时,我必须继承 Documentation 中给出的 BaseBackend。 所以 backend.py 应该是这样的。

    from django.db import models
    from django.db.models.base import Model
    from .models import AdminUsers
    import bcrypt
    from django.contrib.auth.backends import BaseBackend
    
    class CustomAuthentication(BaseBackend):
        def authenticate(self,request,username=None,password=None):
            if username is not None and password is not None:
                user = AdminUsers.objects.get(username=username)
                hashed_password = user.password
                is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
                if is_check == True:
                    return user
                else:
                    return None
            else:
                return None
        
        def get_user(self,user_id):
            user = AdminUsers.objects.get(id=user_id)
            if user is not None:
                return user
            else:
                return None
            
    
    
    

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2019-05-09
      • 2020-03-16
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多