Author: imtech my.oschina.net/u/4231722/b…

The introduction

Scan code login this function, the earliest should be wechat PC started to do, although a little anti-human function (do not scan code and no other way to log in), but have to say it is still very cool.

The following chart should be familiar to IM developers and casual users alike:

Therefore, the bosses and product managers of IM products have one more demand to throw to programmers since then — “Why did wechat scan login, and ours did not?” .

Well, every time as long as it is some functions of wechat, IM programmers want to shake the pot, it is a little difficult, after all, the bosses will take it for granted that some wechat “I” IM products also have to have.

Since can’t avoid, that can only honestly understand the principle of technology, and then their efforts to masturbate it.

This paper will briefly introduce the technical implementation logic of the scanning code login function, and the actual combination of Taobao, wechat scanning code login function, study and research dACHang mainstream application of technical implementation ideas.

Basic technical Principles

What does the scan login function look like?

First of all, what is the scan code login. Most students now have apps like wechat, QQ and Taobao on their mobile phones. And these apps have their corresponding web side. In order to make it easier and safer for users to log in while using their web pages, it seems natural to use a service that allows users to log in with a swipe of their phone.

The interface effect of scanning code login in several major factories is as follows:

Many friends may feel very magical, the webpage only shows a TWO-DIMENSIONAL code, how does it know which phone swept the two-dimensional code, and log in? What’s more, after login, the user’s information can be displayed directly to the user, which is really amazing.

Scan code login function complete technical logic

1) The coordination logic between web and server: the following is the detailed implementation of this service.

First, when users open the login page of the website, they send a request to the browser server to obtain the login QR code. After receiving the request, the server randomly generates a UUID and stores the ID as the key value in the Redis server. At the same time, an expiration time is set. After the expiration, the user needs to refresh the QR code to obtain it again.

At the same time, the key value and the company’s verification string together, through the TWO-DIMENSIONAL code generation interface, to generate a two-dimensional code picture (two-dimensional code generation, there are many ready-made interface and source code, here is no longer introduced). The IMAGE of the QR code is then returned to the user’s browser along with the UUID.

Once the browser gets the QR code and UUID, it sends a request to the browser every second to check whether the login was successful. The request carries a UUID as an identifier for the current page. The server only stores a UUID as a key value in redis, how can there be user ID information?

There will indeed be user ID information, which is stored in Redis by the mobile server. For details, see “Coordination Logic between mobile Phone and Server”.

2) Coordination logic between mobile terminal and server:

In other words, the browser gets the TWO-DIMENSIONAL code, the two-dimensional code display to the web page, and give the user a prompt: please take out your mobile phone, open a sweep for login.

Users can take out their mobile phone and scan the QR code to get a verification information and a UUID (there are also many demos of the function of scanning the QR code to get a string on the Internet, which will not be described in detail here).

Since the mobile terminal has logged in, when accessing the server of the mobile terminal, the parameter carries a user’s token, which can be resolved to the user’s userId by the server of the mobile terminal. (For security purposes, the value is taken from the token rather than directly transmitted to the server of the mobile terminal. Direct transmission of userId may be intercepted and modified. Tokens are encrypted and there is much less risk of being modified. The mobile terminal takes the parsed data and the user’s token as parameters and sends a verification login request to the server (the server here is a mobile server, and the server on the mobile terminal is different from the server on the web terminal).

After receiving the request, the server compares the authentication information in the parameters to determine whether the request interface is the user login interface. If so, an acknowledgement message is returned to the mobile phone.

After receiving the message, the mobile phone will display the login confirmation box to the user (to prevent the user from misoperation and make the login more humanized). After the user confirms the login operation, the mobile phone sends the request again. After receiving the uuId and userId, the server stores the user’s userId as the value in redis and uses the uuId as the key value pair.

3) Logic for successful login:

Then, when the browser sends a request again, the server on the browser side obtains a user Id and invokes the login method to generate a token on the browser side. When the browser sends a request again, the user information is returned to the browser and the login succeeds. I’m going to store the user ID instead of the user information directly because the user information on the mobile end is not necessarily the same as the user information on the browser end.

4) Detailed technical principles are summarized as follows:

Taobao sweep code login technology to achieve

In this section, we take taobao’s scanning code login as an example to actually study and analyze taobao’s scanning code login implementation logic.

Login screen login.taobao.com/member/logi… The parameters returned are:

Then the request (GET) message looks like this:

https://qrlogin.taobao.com/qrcodelogin/qrcodeLoginCheck.do?

lgToken=2c3b4d53ef0513787bf4ce711ea5ba53&defaulturl=&_ksTS=1540106757739_2804&callback=jsonp2805

The key is lgToken, which is the unique ID of the web page. When the two-dimensional code is opened to log in, the web page invokes the interface to request the server in polling (should be long polling). Extension: Thoroughly understand cookie, session, token

If no code is scanned, the return is:

If it does, it returns:

    {

      "code": "10001",

      "message": "mobile scan QRCode success",

      "success": true

  }
Copy the code

No scanning code for a long time, the web end will stop polling, two-dimensional code failure!

After the mobile phone confirms login, the interface returns the following message:

{ "code": "10006", "success": true, "url": "https://login.taobao.com/member/loginByIm.do?uid=cntaobaoxxx&token=ff82fc0d1d395a33d3b38ec5a4981336&time=1530179143250& asker=qrcodelogin&ask_version=1.0.0&defaulturl=https://www.taobao.com & webpas = 0 b7aed2d43f01825183e4a49c6cae47d1479929926" }Copy the code

The interaction between the mobile terminal and the server after clicking “Confirm login” may look like this: The lgToken generated by the web page requests the server. The server remembers the lgToken and thinks it is logged in. When the web page polls the request interface again, it returns the real login Token, and the web page can log in with this Token.

The detailed technical logic is shown in the figure below:

Wechat scan code login technology implementation

Technical principle flow chart

Wechat webpage version visit address is: wx.qq.com/, interested can also go deep…

The actual technology implements logic

1) Obtain the unique UUID and the TWO-DIMENSIONAL code containing the UID information:

GetUUID: function() {vare = t. doffer (); returnwindow.QRLogin = {}, $.ajax({ url: i.API_jsLogin, dataType: "script" }).done(function() { 200 == window.QRLogin.code ? e.resolve(window.QRLogin.uuid) : e.reject(window.QRLogin.code) }).fail(function() { e.reject() }), e.promise }Copy the code

2) The browser polls the server to obtain the scanning status:

/ / sweep view code state checkLogin: function (e, a) {varn = t.d efer (), a = a | | 0; returnwindow.code = 0, window.checkLoginPromise = $.ajax({ url: i.API_login + "? loginicon=true&uuid="+ e + "&tip="+ a + "&r="+ ~newDate, dataType: "script", timeout: 35e3 }).done(function() { newRegExp("/"+ location.host + "/"); if(window.redirect_uri && window.redirect_uri.indexOf("/"+ location.host + "/") < 0) returnvoid (location.href = window.redirect_uri); vare = { code: window.code, redirect_uri: window.redirect_uri, userAvatar: window.userAvatar }; n.resolve(e) }).fail(function() { n.reject() }), n.promise }Copy the code

3) Perform corresponding operations according to the code scanning status returned by the server:

408 Scan timeout: If the phone is not scanned or logged in without authorization, the server will block for about 25s and then return to the status code 408 -> the front end to continue polling

400 QR code failure: The QR code will be invalid if it is not scanned within about 5 minutes

201 has swept code: if the phone has swept code, server immediately return a status code, and the basic information of the users (window. Code = 201, window. Code. UserAvator = “…” ), -> The front end continues polling

200 Authorized: if the mobile phone clicks confirm login, the server returns 200 and token -> the front end stops polling, obtains token, and redirects to the target page

Specific code examples are as follows:

Functiono (c) {switch(c.code) {case200: t.newLoginPage(c.redirect_uri).then(function(t) { varo = t.match(/<ret>(.*)<\/ret>/) , r = t.match(/<script>(.*)<\/script>/) , c = t.match(/<skey>(.*)<\/skey>/) , s = t.match(/<wxsid>(.*)<\/wxsid>/) , l = t.match(/<wxuin>(.*)<\/wxuin>/) , d = t.match(/<pass_ticket>(.*)<\/pass_ticket>/) , f = t.match(/<message>(.*)<\/message>/) , u = t.match(/<redirecturl>(.*)<\/redirecturl>/); returnu ? void (window.location.href = u[1]) : o && "0"! = o[1] ? (alert (f && f [1] | | "login failed"), i.r eport (i.A UTH_FAIL_COUNT, 1), the void location. Reload ()) : (e. $emit (" newLoginPage, "{Ret: o && o[1], SKey: c && c[1], Sid: s && s[1], Uin: l && l[1], Passticket: d && d[1], Code: r }), void (a.getCookie("webwx_data_ticket") || n.report(n.ReportType.cookieError, { text: "Webwx_data_ticket ticket missing ", cookie: document.cookie})))}); break; case201: e.isScan = ! 0, n.report(n.ReportType.timing, { timing: { scan: Date.now() } }), t.checkLogin(e.uuid).then(o, function(t) { ! t && window.checkLoginPromise && (e.isBrokenNetwork = ! 0)}); break; case408: t.checkLogin(e.uuid).then(o, function(t) { ! t && window.checkLoginPromise && (e.isBrokenNetwork = ! 0)}); break; case400: case500: case0: vars = a.getCookie("refreshTimes") || 0; s < 5 ? (s++, a.setCookie("refreshTimes", s, .5), document.location.reload()) : e.isNeedRefresh = ! 0; break; case202: e.isScan = ! 1, e.isAssociationLogin = ! 1, a.setCookie("login_frequency", 0, 2), window.checkLoginPromise && (window.checkLoginPromise.abort(), window.checkLoginPromise = null), r() } e.code = c.code, e.userAvatar = c.userAvatar, a.log("get code", c.code) }Copy the code

summary

JSONP is used to return polling data when scanning code login on wechat web, which is to solve cross-domain problems. If you are not familiar with JSONP, please refer to:

www.52im.net/thread-1038…

When the wechat web terminal scans the code for login, the polling adopts the background to block the foreground request according to the code scanning condition, so as to optimize the polling and reduce the invalid polling in the front end. For this technique, please see:

www.52im.net/thread-338-…

This article summary

Scan code login this function, now has not only appeared in IM applications, all kinds of online websites with mobile terminals also have this function, so the technical principle introduced in this article is not limited to the REALIZATION of SCAN code login in IM applications.

In addition, in order to facilitate the capture of real data for analysis and research, the PC side case analysis in this paper is aimed at the web side, but in fact, if your PC side is a rich client (that is,.exe,.dmg and other installed versions), the principle is the same, and there is no need to consider the cross-domain problems in the browser.

While reading this article, it may involve the traditional Web side instant messaging technology (in order to scan the real-time login), such as long polling, etc. If you are not familiar with these technologies, you can systematically study the Web side instant messaging information organized by instant Messaging network.