Manually logging in a user without password

前端 未结 5 2021
暖寄归人
暖寄归人 2020-12-07 10:18

I hope you can help me figure the best way to implement a manual (server-side initiated) login without using the password. Let me explain the workflow:

5条回答
  •  不知归路
    2020-12-07 10:51

    Response to dan's answer.

    A way to write your backend:

    from django.contrib.auth import get_user_model
    from django.contrib.auth.backends import ModelBackend
    
    class HashModelBackend(ModelBackend):
    
    def authenticate(self, username=None, **kwargs):
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
            return user
        except UserModel.DoesNotExist:
            return None
    

    Answer is based on django.contrib.auth.backends.ModelBackend source code. It's actual for django 1.9

    And I would rather place custom backend below django's default:

    AUTHENTICATION_BACKENDS = [
        'django.contrib.auth.backends.ModelBackend',
        'yours.HashModelBackend',
    ]
    

    because account activation is less possible than login itself. According to https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#specifying-authentication-backends:

    The order of AUTHENTICATION_BACKENDS matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match.

    Be careful this code will authenticate your users even with incorrect passwords.

提交回复
热议问题