vue login to different accounts in the same browser and overwrite the token

There is no problem logging in different accounts with the same browser, but there may be major problems. The second login will overwrite the token of the first login, resulting in the second login user operating some data of the first login. Here is a solution.

1. Log in to account A in the login window, and then copy the same url to log in to account B

For simple A login, and then change to B login. As long as you log in, you can jump to any place. For simple processing, go directly to the code main js

outer.beforeEach((to,from,next) => { //Here, the following operations will be performed before all route jumps
  if(to.path == '/'){ //If you want to go to the login page
    next() //Go wherever you like
  } else { //otherwise
    if(localStorage.getItem('token')){ //Judge whether the current browser has login user information
      next() //Yes, casual, whatever you like
    } else { //Otherwise,
      next({path:'/'}) //Go to the landing page
    }
  }
})

The token here is the key token returned by the background when the user logs in to the system

	localStorage.setItem("token", 1)

Here you will ask why you save localStorage instead of sessionStore. I'll explain to you
localStorage: local cache. There is no time limit. It will always be cached locally.
sessionStorage: session cache, that is, clear the cached data when the browser is closed.
There is a situation to be noted. Remember to clear the cache when exiting, otherwise the local will be kept all the time

1.Set cache data:localStorage.setItem(key,value);
2.Get cached data: localStorage.getItem(key);
3.Get all cached data: localStorage.valueOf();
4.Gets the of the specified subscript key Key value: localStorage.key(N);
5.Delete cached data: localStorage.removeItem(key) ;
6.Clear cached data: localStorage.clear();

2. Window 1 logs in to account A and stays on some pre operation pages. At this time, log in to account B

At this time, the logged in account B will replace the login token of a, and then the page of account a may be tampered with by account B. A's query may find the number of account B. if the permissions are different, the content displayed on the page must be inconsistent. How to correctly avoid these problems?

Back end processing: when all logins operate the data, they check whether it belongs to their own name or not, and directly report errors and throw exceptions. However, this information cannot be avoided. Account A can query the information of account B, which will lead to the disclosure of account information. The method cannot be applied, but it can avoid the operation of data in another way.

In front-end processing, the front-end needs to monitor whether the browser has executed account login in a new window and detect what is stored locally in the browser. However, watch cannot monitor the data stored by non vue mechanism. The data in localStorage cannot be obtained in real time or put into vuex. Vuex will be reset when other accounts log in, and it will not be obtained.

Correct implementation: create a new file and a global variable globalToken to be referenced by the component. In this way, watch will detect the global variable. The thing to do is that the global variable cannot be overwritten by other windows. Log in to the component login The face changing globalToken is introduced into Vue and assigned after successful login

//First introduce variables
import global from '@/config/common.js'
methods: {
  login () {
    if (this.user == '') {
          this.$message.error('Account number cannot be empty!');  //Account verification
        } else if (this.password == '') {
          this.$message.error('Password cannot be empty!'); //password verifiers 
        } else {
          this.setCookie(this.user)    
          this.$post('/api/manage/user/login', {
            userName: this.user,
            passWord: this.password
          }).then(res => {
              localStorage.setItem("token", 1)
              global.token= res.token // Assign to global variable
              localStorage.setItem('userId', res.token) //At the same time, save the token to the local localStorage
              this.$router.push({path: '/container'})
            })
            .catch(err => {
              this.$message.error(err.msg)
            })
        }
      }
  }

In the above code, after successful login, a token will be saved in the global variable, and then a token will be saved in the local localStorage,
main.js Li

import global from '@/config/common.js'    //Introducing global variables
window.addEventListener("visibilitychange",function(){ //Detect browser changes and execute the method
  if (document.hidden == false && global.aaa != localStorage.getItem('userId')) {
    global.token= localStorage.getItem('userId') //The currently logged in user information is different from the user information stored globally. Overwrite the new user information, otherwise it is the initially set value
  }
});

Finally, in app Vue monitors the changes of this global variable to refresh the interface data in real time

watch: {
    'global.token' : 'refresh'
  },
methods: {
   refresh () {
  		//Now the app The header component, menu component and content component under Vue are all refreshed to achieve real-time synchronization
        this.hackReset = false
        this.$nextTick(() => {
          this.hackReset = true
        })
      }
}

At this time, the second window B logs in and returns to the first window A logs in. The whole page will refresh all page data at the same time. The effect is realized and the desired purpose is achieved.
Finish the work!!!!

Provide ideas and solve problems by yourself!! Maybe you will have a better idea!!!

Keywords: Front-end Vue.js Cache

Added by bigshwa05 on Thu, 27 Jan 2022 22:51:50 +0200