django authentication without a password

后端 未结 4 1563
既然无缘
既然无缘 2020-12-05 03:13

I\'m using the default authentication system with django, but I\'ve added on an OpenID library, where I can authenticate users via OpenID. What I\'d like to do is log them

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 03:26

    It's straightforward to write a custom authentication backend for this. If you create yourapp/auth_backend.py with the following contents:

    from django.contrib.auth.backends import ModelBackend
    from django.contrib.auth.models import User
    
    
    class PasswordlessAuthBackend(ModelBackend):
        """Log in to Django without providing a password.
    
        """
        def authenticate(self, username=None):
            try:
                return User.objects.get(username=username)
            except User.DoesNotExist:
                return None
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    Then add to your settings.py:

    AUTHENTICATION_BACKENDS = (
        # ... your other backends
        'yourapp.auth_backend.PasswordlessAuthBackend',
    )
    

    In your view, you can now call authenticate without a password:

    user = authenticate(username=user.username)
    login(request, user)
    

提交回复
热议问题