1 Introduction

After the company has done a good automation of function test, performance test, security test and so on, it urgently needs an MIS system to uniformly manage these results and reports.

The MIS system has the following characteristics:

  • For internal use only
  • Deployed on the Public Network

Based on the above characteristics, it is obviously unrealistic for the company to realize a complete account for such an internal system. In order to meet the requirements of privacy and convenience, the author thinks of using wechat scan code login as identity authentication, and then background administrator review, so as to achieve the following effects:

  • It can realize no threshold registration (a swipe on wechat to complete registration), ensuring convenience
  • The system isolates those who fail to pass the audit to ensure privacy

Then after the development of this system, I feel it is necessary to summarize and sublimate a little, so I have the motivation to write this article.

2 Principle of Multiple Accounts

The original purpose of this paper is to “achieve wechat scan code login”, but later felt that just to achieve this function, the idea of this paper is too low. Therefore, the extension here is “multi-account authorized login system”.

In recent years, with the Internet more and more development and collaboration, the current system login way is also more and more, has gone far beyond the previous single user name way. In addition to the user name and password, common websites also provide the following login methods:

    • Third Party Authorization

      Wechat /QQ/ Sina Weibo (Domestic) Google/Facebook/Github (overseas)

    • Binding account

      Mobile phone number Email number

Based on the above login methods, the following “Multi-account Login System diagram” is formed:

Basic Principles:

    • Third Party Authorization

      You can obtain the corresponding return value (user information) from a trusted third party and bind it to user_id without entering an additional password to complete the authentication process. You can create a set of user_id that can be changed later as placeholders and set the session status after the authentication is successful

    • Binding account

      The user_id has been registered and the corresponding account has been bound. That is, both user_id and user_id can log in to the system using the same or different password system (generally the same password is used). After the authentication is complete, set the session status

The way of binding account is relatively simple, so I will not repeat it here.

Based on the third party authorization, is more sophisticated, can learn more strong, because based on the more and more open characteristics of the Internet, this method will be more and more applied, more and more become the mainstream. The following will take wechat scanning code authorized login as an example to explain.

3 Scan code login logic

The logic diagram of wechat scanning authorization login is as follows:

The main issues dealt with are as follows:

  • Initiates an authentication request to a third party
  • Third-party authentication callback
  • Associate with the local user_id system of the MIS system (new user)
  • Set the session login status
  • Display interface for handling different results

4. Wechat code scanning process

People who have used the wechat scanning code login system will have the following process experience (taking the famous social networking website Zhihu as an example) :

  1. Open the homepage of Zhihu and click the icon of “wechat Login”
  2. The browser redirects to the QR code page below the wechat domain (see mark 1 below)
  3. Users pull out their phones, open wechat and scan
  4. Click Authorization on wechat on your mobile phone
  5. The TWO-DIMENSIONAL code page on the PC shows that the authorization is successful, and turns to the home page of Zhihu, indicating that the authentication is successful

The whole process for the end user, only a few seconds, and do not need to enter any password, can be said to be a very secure and convenient experience.

Then the question comes. What happened in just a few seconds when I scanned the QR code through wechat and completed the registration and login of MIS system?

Several key communication processes are analyzed through browser packet capture.

The PC browser initiates two long connection requests in turn:

  • Waiting for the wechat scan code of the mobile terminal (mark 2 in the above picture)
  • Wait for wechat to click “Confirm login” button (mark 3 in the above picture)

These two states will be fed back to the TWO-DIMENSIONAL code page of the PC terminal. After confirmation on the mobile terminal, the page on the PC browser will be directed to the authorized page (such as the home page of Zhihu).

The communication sequence diagram of the parties is as follows:

The figure above clearly describes the objects involved in the communication in the whole process, and the annotations on the figure above are as follows:

  1. The website server passes a parameter with a callback URL to the wechat API
  2. Wechat mobile phone through the camera scanning two-dimensional code, from the optical principle to complete the data transfer
  3. The long link that queries the scan status on the PC browser receives the returned status value and updates the message
  4. The PC browser queries the status value of the confirm button clicked by the mobile client, updates the prompt, and then redirects to the TRANSFER URL address in procedure 1
  5. After the successful authorization, the web server will complete the business logic of user registration or login of the system
  6. The web server redirects the user to the successful login screen (if no additional audit is required for newly registered users)

As for the development of the scanning code authentication part of wechat, this paper will not repeat it, but only give the following points for attention:

  • Please refer to official documents provided by wechat Open Platform for various API interfaces
  • The development permission of wechat scanning code login requires enterprise qualification authentication in wechat open platform (individual users cannot obtain it).
  • The callback URL field must be filled in and recorded in wechat open platform, and the callback URL parameters passed during local development must be consistent with the record

5 Code Implementation

According to the above principles, the final will provide specific implementation code for reference, for the sake of simplicity, there are some general tool function specific implementation will not be posted.

The reference code for logging in to the Web application using python3.5 for wechat scanning is shown below.

Corresponding to the code in label 1 above:

class WeChatAuth(MyBaseHandler):
    Click and redirect directly to wechat login interface - wechat QR scan code login, Web - redirect directly to wechat page

    def get(self):
        state = get_uuid1_key()  # generate unique code

        wx_qr_param = dict(
            appid=wx_webapp.appid,
            # redirect_uri=wx_webapp.qr_auth_cb_url,
            redirect_uri='http://your.domain.com/wechat/wechat-auth-callback/',
            response_type='code',
            scope=wx_webapp.login_scope,
            state=state
        )  ##wechat_redirect

        wx_qr_url = 'https://open.weixin.qq.com/connect/qrconnect?%s#wechat_redirect' \
                    % urllib.parse.urlencode(wx_qr_param)

        self.redirect(wx_qr_url)
        
Copy the code
class WeChatAuthCallback(MyBaseHandler):
    """ After wechat third-party authentication, the user is deposited in the system - used for the wechat server to return the value of code - here the access_token is requested again.

    async def get(self):
        wx_code = self.get_argument('code'.' ')
        wx_state = self.get_argument('state'.' ')

        if wx_code == ' ':
            res = ConstData.msg_forbidden
            dlog.debug(res)
            self.write(res)
            return

        dlog.debug('wx_code:%s,wx_state:%s' % (wx_code, wx_state))

        access_token_res = wx_webapp.get_auth_access_token(code=wx_code, state=wx_state)
        user_info = wx_webapp.get_auth_user_info(auth_access_token_res=access_token_res)
        """:type:WeChatUser"""  # the user information string returned by wechat

        if user_info is None:
            res = ConstData.msg_forbidden
            dlog.debug(res)
            self.write(res)
            return

        wechat_user = await MisWeChatUser.objects.get(openid=user_info.openid, unionid=user_info.unionid)
        """:type:MisWeChatUser"""
        All ids under Open_id are identified by union

        if wechat_user is not None:
            user = await User.objects.get(user_id=wechat_user.user_id)
            assert user is not None
            if user.active:
                if await user.is_online():
                    await self.update_session()  # Update time
                else:
                    await self.create_session(user)  Add a session
                self.write('in authorized page')
                # self.redirect('/') # todo redirects to the home page after login authorization
                return

        # If there is no wechat record information, you need to record wechat information and register a new initial account
        default_new_user_id = 'u_' + get_uuid1_key()

        new_wechat_user = MisWeChatUser(
            openid=user_info.openid,
            nickname=user_info.nickname,
            unionid=user_info.unionid,
            # user_id= wx_webapp.appId + '_' + user_Info. unionID, # a unique user name generated by wechat login, can be changed later
            user_id=default_new_user_id,
            appid=wx_webapp.appid
        )
        new_wechat_user.set_default_rc_tag()

        # rand_salt = get_rand_salt()
        new_user = User(
            user_id=default_new_user_id,
            # salt=rand_salt, # random number to prevent md5 from reverse cracking
            # passwd=StringField() # password, default is not set for login through third party
            first_name=user_info.nickname,
            status=FieldDict.user_status_init,  # indicates a changeable state
            active=False,
        )
        new_user.set_default_rc_tag()

        await new_wechat_user.save()
        await new_user.save()
        self.write('in unauthorized page')

        # self.redirect(URL_ROOT) # todo import to unauthorized pages
Copy the code

6 Functional Test

Design two sets of test cases.

Check whether wechat users can complete the above process after scanning codes:

  1. Scan the code of A wechat account to log in and check whether automatic registration is required
  2. Will prompt you to redirect to unauthorized page?

In the database, change the status of A’s wechat auto-registered user to scan code for login after approval:

  1. Change the status of user A to Active =True
  2. Is it prompted to redirect to the Authorization page?
  3. Whether the session state of the login is seen in the database

Test screenshots are as follows:

summary

If I am a product manager, if I do a web application products, so in the early period of the product, I would definitely choose WeChat login way, because this way login threshold is too low, the threshold of the user trial products also dropped to the lowest, the subsequent activity at least not under the influence of the threshold of the login.