Taobao and micro-channel scan code login, technically how to achieve?

Click on " technology leadership " concern Δ every day at 8:30 am Push  

Author: Imtech 

my.oschina.net/u/4231722/blog/3154805

1 Introduction

Scan code to log this feature, the first should be the PC side began to engage in micro-channel, though a bit against humanity functions (scan code did not otherwise log in), but have to say is pretty cool.

The picture below, regardless of IM users or ordinary developer, you should be familiar with:

So, engage in IM product owners and product managers, from the addition of a programmer who needs to be thrown - "Why are believed to have micro sweep the login, and we do not?."

Well, every time as long as there is a micro-channel function, IM programmers who want to dump the pot, the difficulty a bit big, after all, would assume that the bosses are, and some micro letter "I" in IM products have to have.

Since we can not avoid, you can only get to know the technical principles of honest, hard line and then own it.

This article will briefly introduce technology to log scan code to implement logic functions, and the realities of Taobao, scan code login feature micro-letters, learning and research applications of technology giant mainstream thinking.

2, the basic technical principles

2.1 scan code login feature in the end is what?

What is at first introduced the scan code to log on. Now most of the students are equipped with micro letter, qq and Taobao this type of software on your phone. These app have their corresponding web client. To allow users to log more convenient and safe when using their web page, use the phone sweep the service can log in, it is a natural.

Several major manufacturers use interface sweeping effect when login code as follows:

There are many small partners may feel very magical, the page just shows a two-dimensional code, how would it know which phone to sweep the two-dimensional code, and to sign it? Moreover, after the registration is completed, the user can direct the information to the user, it is really amazing ah.

2.2 scan code login feature complete technical logic

1) with the mating end of a logical web server:

The next step is for the detailed implementation of this service.

首先用户打开网站的登录页面的时候,向浏览器的服务器发送获取登录二维码的请求。服务器收到请求后,随机生成一个uuid,将这个id作为key值存入redis服务器,同时设置一个过期时间,再过期后,用户登录二维码需要进行刷新重新获取。

同时,将这个key值和本公司的验证字符串合在一起,通过二维码生成接口,生成一个二维码的图片(二维码生成,网上有很多现成的接口和源码,这里不再介绍)。然后,将二维码图片和uuid一起返回给用户浏览器。

浏览器拿到二维码和uuid后,会每隔一秒向浏览器发送一次,登录是否成功的请求。请求中携带有uuid作为当前页面的标识符。这里有的同学就会奇怪了,服务器只存了个uuid在redis中作为key值,怎么会有用户的id信息呢?

这里确实会有用户的id信息,这个id信息是由手机服务器存入redis中的。具体请继续阅读“手机端与服务器的配合逻辑”。

2)手机端与服务器的配合逻辑:

话说,浏览器拿到二维码后,将二维码展示到网页上,并给用户一个提示:请掏出您的手机,打开扫一扫进行登录。

用户拿出手机扫描二维码,就可以得到一个验证信息和一个uuid(扫描二维码获取字符串的功能在网上同样有很多demo,这里就不详细介绍了)。

由于手机端已经进行过了登录,在访问手机端的服务器的时候,参数中都携带一个用户的token,手机端服务器可以从中解析到用户的userId(这里从token中取值而不是手机端直接传userid是为了安全,直接传userid可能会被截获和修改,token是加密的,被修改的风险会小很多)。手机端将解析到的数据和用户token一起作为参数,向服务器发送验证登录请求(这里的服务器是手机服务器,手机端的服务器跟网页端服务器不是同一台服务器)。

服务器收到请求后,首先对比参数中的验证信息,确定是否为用户登录请求接口。如果是,返回一个确认信息给手机端。

手机端收到返回后,将登录确认框显示给用户(防止用户误操作,同时使登录更加人性化)。用户确认是进行的登录操作后,手机再次发送请求。服务器拿到uuId和userId后,将用户的userid作为value值存入redis中以uuid作为key的键值对中。

3)登录成功时的逻辑:

然后,浏览器再次发送请求的时候,浏览器端的服务器就可以得到一个用户Id,并调用登录的方法,生成一个浏览器端的token,再浏览器再次发送请求的时候,将用户信息返回给浏览器,登录成功。这里存储用户id而不是直接存储用户信息是因为,手机端的用户信息,不一定是和浏览器端的用户信息完全一致。

4)详细的技术原理总结如下图所示:

3、淘宝的扫码登录技术实现

本节我们以淘宝的扫码登录为例,来实际研究分析一下淘宝的扫码登录实现逻辑。

登录界面 https://login.taobao.com/member/login.jhtml 传回来的参数为:

然后请求(GET)报文是这样的:

https://qrlogin.taobao.com/qrcodelogin/qrcodeLoginCheck.do?
lgToken=2c3b4d53ef0513787bf4ce711ea5ba53&defaulturl=&_ksTS=1540106757739_2804&callback=jsonp2805

关键的就是lgToken,是网页的唯一ID,当打开了二维码登录的时候,网页在轮询(应该是长轮询long polling)调用接口去请求服务器。扩展:彻底理解cookie,session,token

如果没有扫码,返回的为:

如果扫了的话则会返回:

{

    "code": "10001",

    "message": "mobile scan QRCode success",

    "success": true

}

长时间没有扫码的话,网页端会停止轮询,二维码失效!

当手机端确认登录后,接口返回的是:


"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=0b7aed2d43f01825183e4a49c6cae47d1479929926"
}

表示登录成功,当然手机端与服务端在点击"确认登录"之间的交互可能就是这样:网页端生成的lgToken去请求服务端,服务端记住了这个lgToken并认为登录了,当网页端再次轮询请求接口时,就返回真正的登录态Token,网页端此时就可以凭着这个Token来登录了。

详细的技术逻辑如下图所示:

4、微信的扫码登录技术实现

4.1 技术原理流程图

微信的网页版访问地址是:https://wx.qq.com/,有兴趣也可以自行深入研究。

4.2 实际的技术实现逻辑

1)获取唯一的uuid, 以及包含uid信息的二维码:

// 获取uuid

getUUID: function() {

    vare = t.defer();

    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

}

2)浏览器轮询服务器,获取扫码状态:

// 查看扫码状态

checkLogin: function(e, a) {

    varn = t.defer()

        , 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

}

3)根据服务器返回的扫码状态,进行相应的操作:

408 扫码超时:如果手机没有扫码或没有授权登录,服务器会阻塞约25s,然后返回状态码 408 -> 前端继续轮询

400 二维码失效:大约5分钟的时间内不扫码,二维码失效

201 已扫码:如果手机已经扫码,服务器立即返回状态码和用户的基本信息 (window.code=201,window.code.userAvator="…"),-> 前端继续轮询

200 已授权:如果手机点击了确认登录,服务器返回200及token -> 前端停止轮询, 获取到token,重定向到目标页

具体的代码示例如下:

// 根据服务器返回的扫码状态,进行相应的操作

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] || "登录失败"),
            i.report(i.AUTH_FAIL_COUNT, 1),
            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 票据丢失",
                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)

}

4.3 小结

微信网页端扫码登录时,轮询的数据返回采用的是JSONP的形式,这是为了解决跨域问题。如对JSONP不了解的,可以参考:

http://www.52im.net/thread-1038-1-1.html

微信网页端扫码登录时,轮询采用了后台根据扫码情况阻塞前台请求,优化轮询及减少前端的无效轮询。这种技术,请详见:

http://www.52im.net/thread-338-1-1.html

5、本文小结

扫码登录这个功能,现在已经不只出现有IM应用里,各种带有移动端的线上网站也都有了这个功能,所以本文中介绍的技术原理并不局限于只用于实现IM应用中的扫码登录。

另外,为了方便抓取真实的数据进行分析研究,本文中的PC端案例分析是针对的是网页端,但实际上如果你的PC端是富客户端(也就是.exe、.dmg这样的安装版),原理也是一样的,而且还不需要考虑浏览器里的跨域问题等。

阅读本文时,可能涉及到传统的Web端即时通讯技术(为了扫码登录的实时性),比如长轮询等,如果您对这些技术还不太了解的话,可以系统学习一下即时通讯网整理的有关Web端即时通讯方面的资料。

关注下面公号,回复关键词「中台」即可获取阿里中台50页ppt

“技术领导力”公众号

想加入社区,跟100位互联网大咖学习?

添加群助理Emma,注明“加群”

技术领导力社群


大家在看:

1.在家办公,资深自由职业者的10点建议

2.究竟,钉钉和小学生哪一个先崩溃?

3.职场人接下来会很难!以及我的5个建议

4.“下周集中办公,你该如何防护?”

5.阿里王坚:真正的理想主义,都是拿命来填

写得不错,手动点赞!

发布了149 篇原创文章 · 获赞 671 · 访问量 15万+

Guess you like

Origin blog.csdn.net/yellowzf3/article/details/104322860