Use Django to implement WeChat public account user openid login authentication

Recently, I am working on a small project with Django, and I need to associate WeChat users with website users. Since it is a WeChat subscription account, it does not have the authority to authorize the oauth webpage, so I can only settle for the next best thing, and obtain the user's openid in the response. to uniquely identify the user.

The user model in Django inherits and extends from AbstractUser, and adds the openid field to the user model:
models.py

class Users(AbstractUser):
    openid = models.CharField(max_length=100,blank=True,null=True,verbose_name="openid",unique=True)

We extend the user model and use this model as the user authentication model. We need to specify the authentication model in the setting.py file (website is the name of the django application, not the project name):

AUTH_USER_MODEL = 'website.Users'
In this way, we can use the Users model defined above to perform user login and registration operations.

A common default Django login authentication is to use authenticate, which is quoted in the Django documentation here:

To authenticate a given username and password, use authenticate()
which receives credentials as keyword arguments, for the default configuration it is username
and password, it will return a User object if the password is valid for the given username.
If the password is invalid, authenticate() returns None.
example:

from django.contrib.auth import authenticate 
user = authenticate(username='john', password='secret') 
if user is not None: 
    if user.is_active: 
        print("User is valid, active and authenticated") 
    else: print("The password is valid, but the account has been disabled!") 
else: print("The username and password were incorrect.")

If authenticate returns the correct User object, we use the login() method to log in the returned User object:

from django.contrib.auth import login
login(request,user)

This completes a basic Django user authentication.

If we want to use other methods for login authentication, such as e-mail, mobile phone number, or the focus of this article: WeChat openid, then we need to customize the authentication method.

It is very convenient to perform custom authentication in Django. It only takes three steps to complete a custom authentication:
1. Write an authentication backend:
an authentication backend is a class that implements two methods: get_user(user_id) and authenticate(* *credentials)
Here, we create a new py file wechatAuth.py to write the authentication backend of openid:

from .models import Users
'''
    微信openid认证登录
'''
class WechatOpenidAuth(object):
    def get_user(self,id_):
        try:
            return Users.objects.get(pk=id_)
        except Users.DoesNotExist:
            return None

    def authenticate(self,openid=None):
        try:
            user = Users.objects.get(openid=openid)
            if user is not None:
                return user
            return None
        except Users.DoesNotExist:
            return None

2. Specify the authentication backend in the configuration file setting.py:
At the bottom level, Django maintains a list of "authentication backends".
When calling django.contrib.auth.authenticate(), Django will try all authentication backends for authentication.
If the first authentication method fails, Django will try the second, and so on, until all authentication backends have been tried.
The authentication backend used is specified by the AUTHENTICATION_BACKENDS setting.

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'website.wechat_auth.WechatOpenidAuth',
)
The first authentication backend is Django's default authentication method, because it needs to be used on the web side, so keep it, the second One is the authentication backend based on openid.

3. Use a custom authentication backend to process login authorization:
the same use the authenticate() method and the login() method, but we only pass in one parameter, which is openid

from django.contrib.auth import login,authenticate
def auth(request,openid):
  try:
        auth =authenticate(openid=openid)
        login(request,auth)
        print("登录成功",auth)
  except Exception as e:
        print(e)

In this way, an openid-based authentication is completed.

In WeChat's subscription account, we can use the click event to return a text message or graphic message, with the openid parameter in its link. In this way, when the user clicks the link, the user's login can be completed silently.

=========================================================

original information

The article is first published: http://zmister.com
original link
WeChat public account: Mr. Zhou updated synchronously

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325063980&siteId=291194637