Code scanning login principle + code analysis + complete dome

Posted by morphius on Sun, 09 Jan 2022 12:05:20 +0100

1. Introduction

The function of scanning code to log in should be started at the PC end of wechat at the earliest. It must be said that it is still very magical.

This paper will briefly introduce the technical implementation logic of code scanning login function

1, Basic technical principles

a. What is the code scanning login function?

First, introduce what is code scanning login. Now most students' mobile phones are equipped with software such as wechat, qq and Taobao. These app s have their corresponding web side. In order to make it more convenient and safe for users to log in when using their web pages, it is natural to use the service that users can log in by scanning their mobile phones

The interface effects of code scanning login in several mainstream large factories are as follows:

Many small partners may feel very magical. Only a QR code is displayed on the web page. How can it know which mobile phone has scanned the QR code and logged in? Moreover, after logging in, you can directly display user information to users. It's really amazing. Next, let's look at the principle

b. Complete technical logic of code scanning login function

(1) Web side

First, when the user opens the login page of the website and selects code scanning login, he will send a request to the server to obtain the login QR code. After receiving the request, the server randomly generates a uuid, stores the id as the key value in the redis server, and sets an expiration time and code scanning status. After expiration, the user needs to refresh and re obtain the login QR code.

More often, this key value is combined with the company's verification string to generate a QR code image through the QR code generation interface, and then return the QR code image and UUID to the browser, or return the UUID and expiration time to the browser, and the front end generates a QR code.

After the browser generates the QR code, it will send a login success request to the server every second to judge whether the user has completed scanning the code, completed login or expired the QR code. The request carries uuid as the current identifier.

(2) Mobile terminal

After getting the QR code, the browser will display the QR code on the web page and give the user a prompt: please scan the QR code to log in;

The user takes out the mobile phone and scans the QR code to get an authentication information and a uuid

Since the mobile terminal has logged in, a request will be sent to the server when the QR code is scanned and parsed, and a user's token will be carried in the parameters, The server can parse the user's userid from it (here, the value is taken from the token instead of directly transmitting the userid from the mobile terminal for security. Directly transmitting the userid may be intercepted and modified. The token is encrypted, and the risk of modification will be much smaller. I'm in the following dome for convenience)

After code scanning is completed, first send a code scanning completion request to the server
After receiving the request, the server first compares the authentication information in the parameters to determine whether it is the user login request interface. If yes, first modify the code scanning status of this UUID in the redis server to code scanning, and the browser will prompt the user to click login after receiving the data, and then return a confirmation message to the mobile terminal,

After receiving the return, the mobile terminal displays the login confirmation box to the user (direct login without clicking login is anti-human and interactive. If you need to scan the code to log in directly, just delete this step). After the user confirms the login operation, the mobile phone sends the request again. After getting the UUID and userid, the server stores the user's userid as the value value into the key value pair with UUID as the key in redis.

(3) Login succeeded

Then, when the browser continues to send the request, the browser can get a user ID and call the login method to generate a browser token. When the browser sends the request again, the user information is returned to the browser, and the login is successful. The reason why the user ID is stored here instead of directly storing the user information is that the user information on the mobile phone is not necessarily completely consistent with the user information on the browser.

This is a picture from IM instant messaging community

2, Simple DOM code parsing

Three parts are required to complete this function first
 1. The web side mainly displays the QR code, and jQuery (QR code generation plug-in) is used
 2. The backend, PHP, does not prepare the redis server here, but directly uses the database
 3. The mobile terminal is used to scan the code and is developed using uniapp

First of all, the back-end simple DOM does not have many functions, just database reading and writing
You need two tables first

1.tap table records the request data, including four fields: unique identifier UUID, expiration time, scanning status isok, scanning account user
2.user table, simulate user data and verify login

How many interfaces are required
1. The QR code request interface generates a unique identifier UUID and expiration time, writes it into the database and returns the UUID and expiration time. There are many methods to generate a unique UUID. I directly use the timestamp as the unique UUID here

$time = time()+300;//time
    $uuid = time();//There are too many methods to generate unique IDs. Time stamps are used directly here
    $sql= "INSERT INTO `tap`(uuid,time,isok,user) VALUES ('$uuid','$time','false','none')";
    $obj=mysqli_query($link,$sql);
    //Write tap table
    if($obj){
        //output
        $results = array(
            'uuid' => $uuid,
            'time' => $time
        );
        $result = array(
            'code' => 0,
            'data' => $results
        );
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }else{
        echo 'An error occurred';
    }

2. Modify the code scanning status to the interface in code scanning. Here, modify the code scanning status to 'ing'

$sql = "UPDATE tap SET isok='ing' WHERE uuid='$uid'";
    //Write to the corresponding account and modify the code scanning status to code scanning
    $obj = mysqli_query($link, $sql);
    if ($obj) {
        echo "true";
    } else {
        echo "false";
    }

3. Write the corresponding UUID code scanning status as code scanning completion and record code scanning account interface

$sql = "UPDATE tap SET isok='true',user='$user' WHERE uuid='$uid'";
    //Write the corresponding account to modify the code scanning status
    $obj = mysqli_query($link, $sql);
    if ($obj) {
        echo "true";
    } else {
        echo "false";
    }

4. Interface to query the data recorded under the unique UUID

header('content-type:application/json;charset=utf8');
    $sql ="SELECT * FROM tap where uuid='$uid'";
    $obj = mysqli_query($link,$sql);
    $total_sql = "SELECT COUNT(*) FROM tap";
    $total_result = mysqli_fetch_assoc(mysqli_query($link, $total_sql));
    $total = $total_result['COUNT(*)'];
    $results = array();
    while ($row = mysqli_fetch_assoc($obj)) {
        $results[] = $row;
    }
    $result = array(
        'code' => 0,
        'message' => "",
        'count' => $total,
        'data' => $results
    );
    if($result){
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }else{
        echo mysql_error();
    }

5. Interface for querying user information

header('content-type:application/json;charset=utf8');
    $sql ="SELECT * FROM users where text='$user'";
    $obj = mysqli_query($link,$sql);
    $total_sql = "SELECT COUNT(*) FROM users";
    $total_result = mysqli_fetch_assoc(mysqli_query($link, $total_sql));
    $total = $total_result['COUNT(*)'];
    $results = array();
    while ($row = mysqli_fetch_assoc($obj)) {
        $results[] = $row;
    }
    $result = array(
        'code' => 0,
        'message' => "",
        'count' => $total,
        'data' => $results
    );
    if($result){
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }else{
        echo mysql_error();
    }

Finally, for the convenience of testing, write an interface to add users

$sql= "INSERT INTO `users`(text,pass,name) VALUES ('$addText','$addPass','$addName')";
    $obj=mysqli_query($link,$sql);
    if($obj){
        echo 'Added successfully';
    }else{
        echo 'An error occurred';
    }

These interfaces have been identified by tap to be called separately

With these interfaces, you can start to complete the specific functions. The next two parts are mobile terminal and web page

First, the user selects the code scanning login function when logging in. At this time, the user requests the back end to generate a unique UUID and expiration time, and generates a two-dimensional code display after receiving the data

First, write the HTML structure, because the QR code is displayed in the code scanning process. When the code scanning is completed, it has expired

        <div id="code"></div>

        <div class=" tw star">
            <p>Loading...</p>
        </div>

        <div class="tw cok">
            <p>Code scanning succeeded</p>
        </div>

        <div class="tw ok">
            <p>Login succeeded</p>
        </div>

        <div class="tw bard">
            <p>An error occurred</p>
        </div>

        <div class="tw time">
            <p>Code scanning timeout</p>
        </div>

Start the request back end, call the interface and get the data

If the request fails, an error is directly displayed
If the request is successful, the obtained UUID will be generated into a QR code and displayed

Then create a timer (int) to poll and query the UUID data interface before the set expiration time to judge whether the code is currently being scanned according to the carried isok (code scanning status). Each poll needs to judge whether it is expired. If it is not expired, continue polling until the code scanning status becomes code scanning

At this time, it has been judged that it is in code scanning. Now close the first timer (int) immediately and modify the page prompt to code scanning

Then create a timer (int2) again. Poll the data interface corresponding to UUID in the timer. Each poll still determines whether it has expired. Continue to poll on the premise that it has not expired to determine whether the code scanning is completed

During the polling process, continuously judge whether the code scanning status is code scanning completed. When the condition is true, immediately close the second timer (int2), and then display that the login has been successful
Next, request the user data interface to return the user data and display it

Get QR code

Scanning code

Code scanning completed

Next is the mobile terminal

When the QR code appears on the page, click the button to start scanning the code

When the QR code content is obtained after code scanning, it is requested to modify the code scanning status to the interface in code scanning,


See the picture directly

When all interfaces return to normal data, jump to the confirmation login interface

After clicking the confirm button, the user requests to modify the code scanning status to code scanning completed, and prompts

At this point, the process ends

Full DOM

Back end construction

1. First, you need to create two tables in the database, the tap table and the user table

tap table

user table

2. Backend configuration database
-Open mysql.config in the config directory INI file
Fill in the database information as shown in the figure

3. Configure page end
After the backend is built, open index HTML file, find 147 lines, modify the back-end api domain name, and the end needs to be marked with / e.g http://baidu,com/ (please put api.php in the root directory)

4. Configure mobile terminal
After setting up the back end, open the uniapp project and open index / index in the pages directory Vue file, modify apiurl in line 23, and the content is the same as the end shadow
Open uigo / uigo.com under pages Vue file, modify line 15

See the end of the article for the download address of the complete package

This is just a dome, which is more complex in actual development, but the principles are the same. In actual development, the server needs to verify the user account and password when modifying the code scanning status, and the uploaded account and password need to be encrypted. Remember

dome Download

Scan the code to log in to the dome Zip - blue cloud

Topics: Java Front-end Mini Program