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

jquery+springboot realizes file upload function

This article example shares the specific code of ...

Exploration of three underlying mechanisms of React global state management

Table of contents Preface props context state Sum...

Example of implementing grouping and deduplication in MySQL table join query

Table of contents Business Logic Data table struc...

HTML Basics Must-Read - Comprehensive Understanding of CSS Style Sheets

CSS (Cascading Style Sheet) is used to beautify H...

HTML pop-up div is very useful to realize mobile centering

Copy code The code is as follows: <!DOCTYPE ht...

Introduction to the use of em in elastic layout in CSS3: How many pixels is 1em?

I have been using CSS for a long time, but I have...

Detailed explanation of overlay network in Docker

Translated from Docker official documentation, or...

How to detect if the current browser is a headless browser with JavaScript

Table of contents What is a headless browser? Why...

Summary of methods to include file contents in HTML files

In the forum, netizens often ask, can I read the ...

Javascript uses the integrity attribute for security verification

Table of contents 1. Import files using script ta...

How to use HTML+CSS to create TG-vision homepage

This time we use HTML+CSS layout to make a prelim...

MySql COALESCE function usage code example

COALESCE is a function that refers to each parame...

Detailed explanation on how to modify the default port of nginx

First find out where the configuration file is wh...