Creating a Simple Authentication Backend(创建一个简单的后端认证)

Creating a Simple Authentication Backend



This is only a simple backend and isn't really useful beyond an example. More experienced users may want to skip this step

For this example we are going to check to see if a user matching the username exists and that the password is their username in reverse.

So, assuming you have a user called admin, the following would be correct;

Username: admin
Password: nimda

# import the User object
from django.contrib.auth.models import User

# Name my backend 'MyCustomBackend'
class MyCustomBackend:

    # Create an authentication method
    # This is called by the standard Django login procedure
    def authenticate(self, username=None, password=None):

            # Try to find a user matching your username
            user = User.objects.get(username=username)

            #  Check the password is the reverse of the username
            if password == username[::-1]:
                # Yes? return the Django user object
                return user
                # No? return None - triggers default login failed
                return None
        except User.DoesNotExist:
            # No user was found, return None - triggers default login failed
            return None

    # Required for your backend to work properly - unchanged in most scenarios
    def get_user(self, user_id):
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Making Django use your new Authentication Backend.

In your add


You might have 'project.backend.MyCustomBackend' - this could be in your project file, with a class name of MyCustomBackend

Yes, security wise this is pretty pointless, but its demonstrating how a simple authentication backend works.
Creating a Custom Authentication Backend


comments powered by Disqus