Let’s look at the implementation first

The front-end principle

After logging in a.com, we need to realize automatic login after b.com is opened. We know that the essential link between the two is mutual communication

However, since browsers are affected by cookie same-origin policies due to security issues, there are two solutions:

The first: the subdomain obtains information by accessing the primary domain

The sub-domain can perfectly obtain cookie information under the primary domain. There is nothing to be said about this scheme, and this scheme is too restrictive, requiring both subsystems to be secondary domains

Second: the two systems store the login information in the other service (also the following implementation scheme)

The login information of each system is passed into the communication system, and each system first tries to obtain the user token from the communication service

If so, the user information can be obtained directly by token login; if not, the user can be logged in normally by means of cross-domain storage

Knowledge theory layer (those with basic knowledge can directly enter the practical layer below)

Window provides an API called postMessage with the following method parameters

otherWindow.postMessage(message, targetOrigin, [transfer]);
Copy the code

OtherWindow A reference to another window, such as the contentWindow property of iframe, the window object returned by executing window.open, or the window.frames named or numeric index.

Message is the data to be sent to the other window. It will be serialized by a structured cloning algorithm. This means you can safely pass data objects to the target window without having to serialize them yourself.

TargetOrigin specifies which Windows can receive message events via the origin property of the window, which can be a string “” (for unrestricted) or a URI. If any of the protocol, host address, or port of the target window does not match the value provided by targetOrigin, the message will not be sent. A message will only be sent if all three match. This mechanism controls which Windows messages can be sent to; For example, this parameter is especially important when a password is sent using postMessage, and its value must be exactly the same as the Origin property of the intended recipient of the message containing the password to prevent the password from being intercepted by a malicious third party. If you know exactly which window the message should be sent to, always provide a targetOrigin with an exact value instead of. Not providing an exact target will result in data being leaked to any malicious site interested in the data.

A Transfer (optional) is a string of Transferable objects that are passed at the same time as Message. Ownership of these objects is transferred to the receiver of the message, and ownership is no longer retained by the sender.

With good things like this, we can set up an accessible page in the communication service, where we store information after each system login

So each of our systems just need to go to the communication service through Ifarme to get information before logging in

In order to facilitate debugging, three ports (server1, server2, loginServer) are enabled locally, and their relationship is roughly as shown in the figure below (for convenience, it does not represent uniqueness).

Front-end code practices

With bullshit like that, go straight to the code

Server to be logged in to

// Login methodfunction login() {
    const name = document.querySelector('.name').value
    const password = document.querySelector('.psw').value
    jQuery.ajax({
        url: 'http://localhost:8083/login',
        method: 'post',
        data: {
            name,
            password
        },
        success: function(res) {
            const resData = JSON.parse(res)
            $('.login').fadeOut(500)
            $('.success').fadeIn(500)
            letSTR = '<div> <p>message:${resData.message}</p>
                </div>`
            $(".success").append(STR) // After login, send the user token to the communication service and save postInfo(resData,'set')}}}function getInfo() {
    return localStorage.getItem('userInfo'} // Send data to the communication servicefunction postInfo(data, func) {
    const ifameWin = document.querySelector("#middle").contentWindow
    let Message = {
        method: func === 'set'? 'setItem' : 'getItem',
        key: 'userInfo',
        value: data || ' '
    }
    ifameWin.postMessage(Message, The '*')
}

window.onload = function() {// Check to see if you have login informationif(getInfo()) {
        $('.login').hide()
        $('.success').show()
        letSTR = '<div> <p> Logged in </p> <p> user name:${localStorage.getItem('userInfo').name}</p> <p> User name:${localStorage.getItem('userInfo').password}</p>
            </div>`
        $(".success").append(str)
    } else{// go to postInfo()} // listen for messages sent from postInfo(window.adDeventListener ())'message'.function(e) {// If there is any information you need, you should not be lazy.if(e.data && JSON.parse(e.data.result)) {
            const data = JSON.parse(e.data.result)
            $('.login').hide()
            $('.success').show()
            letSTR = '<div> <p> Logged in </p> <p> user name:${data.user.name}</p> <p> User name:${data.user.password}</p>
                </div>`
            $(".success").append(str)
        }
    })
}
Copy the code

The server responsible for communication

let objMap = {
    setItem: (key, val) => window.localStorage.setItem(key, JSON.stringify(val)), getItem: (key) = > window. LocalStorage. The getItem (key)} / * * sending a son to monitor system information, according to the requirements of son to do the corresponding * / window. The addEventListener ('message'.function (e) {
    let { method, key, value } = e.data
    let result = objMap[method](key, value)
    let response = {
        result
    }
    window.parent.postMessage(response, The '*')})Copy the code

Okay, so that’s the end of the front end, and then the back end

God said: our system login needs back-end cooperation so the back-end has a login interface

In order to facilitate you to try to modify the back end, so the use of Node.js koA2 to do, communication services page is also placed here for convenience

The client initiates a login request and performs authentication based on the user information. If the authentication succeeds, the token is generated and returned to the client

The author here does not connect the database, even the simple file database did not do, only did the most simple information storage, because I am lazy……

And so on and so on and so on

Here is the end, specific source CODE I have uploaded to Github, interested can down to try their own, github.com/Catlina1996…

The above only represents the personal thinking, is not the only, welcome big guy advice modification!