Vue keeps the user logged in (various token storage methods)

Vue keeps the user logged in (various token storage methods)

In the front end, there are many ways to keep the user logged in. You can keep it by storing Cookies, Sessions, Tokens and other information. No matter which one the background sends to the front end, what we have to do is to store this information in the local browser. When the browser sends the request again, it will throw the Cookie with 'key' = 'value' set to the server again. The server determines that the user has logged in through the Cookie的field, and processes the user request according to the needs, otherwise it returns 400 to prompt the user to log in first. I have also shared related articles before: Django: Cookie settings and cross-domain problem handling, Django: Cookie with Session, Django: Token-based authentication. As a front-end, there are also many ways to store these values. You can store them in Cookies, LocalStorage, SessionStorage or Vuex state manager. Of course, their functions are also different, such as Vue: The difference and usage of LocalStorage and SessionStorage.

Vue practical development 020: the difference and usage of LocalStorage and SessionStorage

How to set cookies

Django can respond to the object's set_cookie through HttpResponse來set_cookie,設置好對應的視圖和路由,只要通過瀏覽器訪問該路由,瀏覽器就會自動獲取到set_cookie值并存入到本地(當瀏覽器正在運行時通常都存在內存中,當瀏覽器關閉時通常會存入硬盤中)。

Django Practice 006: Cookie Settings and Cross-Domain Problem Handling

Disadvantages of Cookies:

1. Small amount of cookie storage; 2. Limited number of cookie storage; 3. Increase network burden; 4. There are security risks

LocalStorage and SessionStorage Token Storage

If stored in SessionStorage, when the user logs in, we need to store the username id and token in sessionStorge. It is also simple to implement in Vue, which can be achieved through sessionStorage.setItem or sessionStorage['token'].

.then(res => {
                    if(res.data['code']==200){
                        localStorage.clear()
                        localStorage.setItem('info',1)
                        localStorage['flag']=1
                        // localStorage.setItem('flag',1)
                        sessionStorage.clear()
                        // sessionStorage['userid'] = JSON.stringify(res.data.userInfo.id)
                        sessionStorage.setItem('userid',JSON.stringify(res.data.userInfo.id))
                        sessionStorage['token'] = JSON.stringify(res.data.token)
                        this.$message({
                            message:'Login successful',
                            type:'success'
                        })
                        this.$router.push('/home')
                    }else{
                        this.$message({
                            message:'Wrong username or password',
                            type:'warning'
                        })
                        }
                })

In this way, we can find Session Storge in the application in the browser's developer tools and check it. The value we just obtained is stored in it. As for whether to store it in LocalStorage or SessionStorage, it depends on the project requirements.

The main differences between LocalStorage and SessionStorage:

LocalStorage is permanently stored in the browser unless you actively delete it.

SessionStorage is only valid before the current window is closed, and its stored data will be automatically cleared after the window is closed.

Vue practical development 020: the difference and usage of LocalStorage and SessionStorage

Vuex Store Token

Initialize the token in the state of the store file. Because the data in the state does not support direct modification, we need to define the methods setToken (set token) and getToken (get token). Then we can introduce this.$store.commit('setToken',JSON.stringify(res.data.token)) at the login interface, and store the token sent from the background in Vuex and localStorage. Why do we need to store it in localStorage? The state in Vuex no longer exists once the page is refreshed. In order to maintain the current state, we need to extract the state from localStorage and then pass the value to Vuex.

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
  state: {
    token:'' // Initialize token
  },
  mutations:
    //Store token method //Set token equal to the value passed in from outside setToken(state, token) {
        state.token = token
        localStorage.token = token //Synchronously store token to localStorage
      },
  },
 getters : {
  //Get token method//Judge whether there is a token. If not, reassign it and return the token to the state
  getToken(state) {
    if (!state.token) {
      state.token = localStorage.getItem('token')
    }
    return state.token
    }
  },
  actions: {
 
  }
})

Why use Vuex?

Vuex is a state manager rather than a storage tool. Why is the token stored in Vuex? The localStorage operation encapsulated in Vuex can directly use localStorage to operate data, but it cannot monitor data changes. Vuex is a global storage that can monitor changes in data status. When the Vuex value changes, the data change can be monitored responsively.

This concludes this article about Vue keeping users logged in (various token storage methods). For more information about Vue keeping users logged in, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementation of judging whether the user is logged in when vue routing jumps
  • Vue.js implements user comment, login, registration, and information modification functions
  • Detailed explanation of how Vue obtains user login information through cookies
  • Example code for saving user login status in Vue
  • Vue implements the automatic login logout function for users who have not operated for a long time
  • vue-router beforeEach jump route to verify user login status
  • How to add user login function in VuePress

<<:  Ubuntu opens port 22

>>:  MySQL GROUP_CONCAT limitation solution

Recommend

React implementation example using Amap (react-amap)

The PC version of React was refactored to use Ama...

Detailed Example of MySQL InnoDB Locking Mechanism

1. InnoDB locking mechanism The InnoDB storage en...

An example of the difference between the id and name attributes in input

I have been making websites for a long time, but I...

Linux general java program startup script code example

Although the frequency of starting the shell is v...

Several skills you must know when making web pages

1. z-index is invalid in IE6. In CSS, the z-index...

Meta tags in simple terms

The META tag, commonly referred to as the tag, is...

An example of implementing a simple finger click animation with CSS3 Animation

This article mainly introduces an example of impl...

Detailed explanation of common template commands in docker-compose.yml files

Note: When writing the docker-compose.yml file, a...

Example code for converting html table data to Json format

The javascript function for converting <table&g...

Ubuntu installation graphics driver and cuda tutorial

Table of contents 1. Uninstall the original drive...

How to understand SELinux under Linux

Table of contents 1. Introduction to SELinux 2. B...

How to use ES6 class inheritance to achieve a gorgeous ball effect

Table of contents introduce Implementation steps ...

About vue component switching, dynamic components, component caching

Table of contents 1. Component switching method M...