自定义authenticate()认证方法 | Django

Posted 胡说八道

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义authenticate()认证方法 | Django相关的知识,希望对你有一定的参考价值。

# 自定义认证方法
# authenticate()方法默认对username与password做验证
    authenticate(username=user_name, password=pass_word)
# 需求:对邮箱或者用户名,与密码共同验证;

# 1.重载settings.py的变量
    AUTHENTICATION_BACKENDS = (
        users.views.CustomBackend
    )
# 2.自定义认证方法
    from django.contrib.auth.backends import ModelBackend
    from .models import UserProfile
    
    class CustomBackend(ModelBackend):
        # 修改认证方法
        def authenticate(self, username=None, password=None, **kwargs):
            try:
                # 根据字段值获取对象
                user = UserProfile.objects.get(Q(username=username)|Q(email=username))
                # 验证密码,返回认证通过对象
                if user.check_password(password):
                    return user
            # 没有输入用户名返回None
            except Exception as e:
                return None

源码:

 

# --------------------------------------------------|ModelBackend基类源码
class ModelBackend(object):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    根据系统配置中指定的User表对象里的字段做认证;
    """

    def authenticate(self, username=None, password=None, **kwargs):
        # Returns the User model that is active in this project.
        UserModel = get_user_model()
        # 如果用户名不存在...
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user (#20760).
            UserModel().set_password(password)
            
    # ----------------------------------------|get_user_model()    
    def get_user_model():
        """
        Returns the User model that is active in this project.
        """
        try:
            return django_apps.get_model(settings.AUTH_USER_MODEL)
        except ValueError:
            raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form ‘app_label.model_name‘")
        except LookupError:
            raise ImproperlyConfigured(
                "AUTH_USER_MODEL refers to model ‘%s‘ that has not been installed" % settings.AUTH_USER_MODEL
            )
# --------------------------------------------------

 

以上是关于自定义authenticate()认证方法 | Django的主要内容,如果未能解决你的问题,请参考以下文章

django中的认证(含自定义认证)与登录

django中的认证(含自定义认证)与登录

认证组件

Django之博客系统:自定义认证

认证 权限 视图 频率

drf认证节流权限版本