django authentication without a password

后端 未结 4 1565
既然无缘
既然无缘 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:33

    In order to do authenticate without password, in your settings.py:

    AUTHENTICATION_BACKENDS = [
    # auth_backend.py implementing Class YourAuth inside yourapp folder
        'yourapp.auth_backend.YourAuth', 
    # Default authentication of Django
        'django.contrib.auth.backends.ModelBackend',
    ]
    

    In your auth_backend.py:

    NOTE: If you have custom model for your app then import from .models CustomUser

    from .models import User 
    from django.conf import settings
    
    # requires to define two functions authenticate and get_user
    
    class YourAuth:  
    
        def authenticate(self, request, username=None):
            try:
                user = User.objects.get(username=username)
                return user
            except User.DoesNotExist:
                return None
            
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    In your Views for custom login request:

    # Your Logic to login user
    userName = authenticate(request, username=uid)
    login(request, userName)
    

    For further reference, use the django documentation here.

提交回复
热议问题