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

How to use CSS media query aspect-ratio less

CSS media query has a very convenient aspect rati...

The difference and introduction of ARGB, RGB and RGBA

ARGB is a color mode, which is the RGB color mode...

Setting up shared folders in Ubuntu virtual machine of VMWare14.0.0

This is my first blog post. Due to time constrain...

Summary of four ways to loop through an array in JS

This article compares and summarizes four ways of...

Implementing WeChat tap animation effect based on CSS3 animation attribute

Seeing the recent popular WeChat tap function, I ...

Example code for configuring monitoring items and aggregated graphics in Zabbix

1. Install Zabbix Agent to monitor the local mach...

Detailed explanation of common commands in Docker repository

Log in docker login Complete the registration and...

Analysis of the HTML writing style and reasons of experienced people

1. Navigation: Unordered List vs. Other Label Ele...

Mysql uses stored procedures to quickly add millions of data sample code

Preface In order to reflect the difference betwee...

Detailed steps to build the TypeScript environment and deploy it to VSCode

Table of contents TypeScript environment construc...

ReactJs Basics Tutorial - Essential Edition

Table of contents 1. Introduction to ReactJS 2. U...

Summary of @ usage in CSS (with examples and explanations)

An at-rule is a declaration that provides instruc...

In-depth analysis of MySQL database transactions and locks

Table of contents 1. Basic Concepts ACID 3.AutoCo...

Detailed explanation of mysql filtering replication ideas

Table of contents mysql filtered replication Impl...