Django custom authentication method usage example

  • 2020-06-07 04:46:09
  • OfStack

This article gives an example of Django custom authentication. To share for your reference, specific as follows:

Create a login application

First, create a new login app to hold the code used for authentication


python manage.py startapp login

Modify the authentication item in ES11en. py


AUTHENTICATION_BACKENDS = (
  'login.auth.UsernamePasswordAuth',
)

Custom authentication classes

Create the auth.py file under login app, as follows


#coding:utf-8
from django.contrib.auth.models import User
class UsernamePasswordAuth(object):
  def authenticate(self, username=None, password=None):
    print("UsernamePasswordAuth.authenticate")
    try:
      user = User.objects.get(username__iexact=username)
      if user.check_password(password):
        return user
    except User.DoesNotExist:
      return None
  def get_user(self, user_id):
    print("UsernamePasswordAuth.get_user")
    try:
      user = User.objects.get(pk=user_id)
      return user
    except User.DoesNotExist:
      return None

For more information about Python, please refer to Python Socket Programming Skills summary, Python URL Operation Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Usage Tips Summary, Python String Operation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: