Detailed explanation of the idea of ​​setting up login verification interception function in Vue

Detailed explanation of the idea of ​​setting up login verification interception function in Vue

Hello, I’m灰小猿, a programmer who is really good at writing bugs!

Today, when I was working on a project where vue and springboot interact, I wanted to implement some operations based on the front end that only allow access to certain pages after login verification, so here is a solution to achieve this function.

First, let me tell you how I determine whether I have logged in.

1. Solution

Since the shiro+Jwt security framework is used in my springboot background, a token will be fed back to the front end after login, and the front end will store the token, so I go to find out whether there is a token in the browser. If there is a token in the browser, it means that the login is successful and you can access the relevant pages;

If there is no token, it means you are not logged in, and j will jump to the login page. In order to simplify the operation, I encapsulated the verification process.

注意: The premise of using this method for verification is that your front-end and back-end are verified through Shiro and token, and the front-end will store the token returned by the server.

2. Let the browser store the token returned by the server

First, let's take a look at how the token returned by the server is stored in the front-end page.

First, I encapsulated a SET_TOKEN method in the index.js file under the store file to store the token in the browser, so that we can get our token from the local every time through localStorage.getItem("token"), and also encapsulated a REMOVE_INFO method to clear the token information in the browser when we log out.

The code in index.js under the store file is as follows:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // token: "",
        //User information can be directly retrieved from the browser token: localStorage.getItem("token"),
        //Deserialization operation userInfo: JSON.parse(sessionStorage.getItem("userInfo"))
    },
    mutations:
        /**Similar to set operation*/
        //Assign value to token SET_TOKEN: (state, token) => {
            state.token = token;
            //Store the information in the browser so that it is still there when the browser is closed localStorage.setItem("token", token);
        },
        //Assign value to userinfo SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo;
            //The session will be cleared every time the browser is closed and regenerated after logging in again. //Since sessionStorage cannot store objects, it must be stored in the form of a string. sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
        },
        //Remove user information REMOVE_INFO: (state) => {
            //When removing user information, set all user information to empty state.token = "";
            state.userInfo = {};
            localStorage.setItem("token", "");
            sessionStorage.setItem("userInfo", JSON.stringify(""));
        }

    },
    getters: {
        /**Similar to get request*/
        //Get user informationgetUser: state => {
            return state.userInfo;
        }
    },
    actions: {},
    modules: {}
})

3. Set access permissions in the request

Since not all of our pages can be accessed only when logged in, we need to set access permissions for pages that require login.

In vue, we usually set the access route in the index.js file under the router. For the request route that needs to add login permissions, we can add a meta attribute to it and set a Boolean attribute requireAuth in it. We will use whether this attribute is true to determine whether login verification is required.

For example, our BlogEdit page can only be accessed when logged in, and the Login page does not require login permissions, so we can set it up like this: (代碼有刪減,但是保留了核心部分,只是刪除了部分路由。)

/**
 * Routing Registry */

import Vue from 'vue'
import VueRouter from 'vue-router'


//Registration page import Login from '../views/Login.vue'
import BlogEdit from '../views/BlogEdit.vue'


Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/blog/add',
        name: 'BlogAdd',
        component: BlogEdit,
        //Add permission access, indicating that this operation can only be performed after logging in meta: {
            requireAuth: true
        }
    },


]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

This will be judged every time the BlogEdit page is requested.

4. Encapsulation login verification

Now we need to write a method to verify the properties we just set. So create a permission.js file in the src directory and encapsulate it.

思路是這樣的: first we intercept the request and get the requireAuth parameter in the request. If the parameter is true, we get the token in the browser to verify whether the current state is logged in. If a token exists, the request is allowed; if no token is obtained, the request is redirected to the login page.

注意: If you log in based on other authentication, you can
//Get the local token
const token = ocalStorage.getItem("token")
Change to your verification method, but the idea is the same.

The code is as follows:

/**
 * Request login verification. If you are not logged in, you cannot access the page and return to the login page*/
import router from "./router";

//Route judgment login, according to the parameters of the routing configuration file router.beforeEach((to,from,next)=>{
    //Determine whether the route requires login permission//record.meta.requireAuth is the parameter carried in the request if (to.matched.some(record => record.meta.requireAuth)){
        //Get the local token
        const token = localStorage.getItem("token")
        console.log("Show token----------: " + token)

        //Judge whether the current token exists, that is, the token used for login
        if (token){
            //If it points to the login page, do nothing if (to.path === "/login"){

            }else {
                //If it is not a login page and the token exists, release next()
            }
        }else {
        // If token does not exist // Go to login next({path:'/login'})
        }

    }else {
        //If login authentication is not required, directly access next()
    }
})

最后別忘了將該頁面引入到mian.js中。

//Import permission.js, users perform front-end permission controlimport "./permission"

To sum up

The main operations are the third and fourth steps. As long as you set the login verification parameters in the request route, write the login interception verification in the fourth step, and introduce it into the main.js file, that's it!

At this point, the login interception is completed through the front-end verification.

This concludes this article on the detailed explanation of the idea of ​​setting up the login verification interception function in Vue. For more relevant vue login verification interception content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue+springboot realizes login verification code
  • Vue implements graphic verification code login
  • Vue implements picture verification code when logging in
  • After successful login verification in Vue, the token is saved, and each request carries and verifies the token operation
  • Vue login intercepts the operation of continuing to jump to the specified page after logging in
  • Two ways to implement login interception in vue+axios front end (routing interception, http interception)
  • Vue axios login request interceptor
  • Example code for implementing login interception with vue+axios

<<:  A brief analysis of MySQL's lru linked list

>>:  Docker deployment nginx implementation process graphic and text detailed explanation

Recommend

Detailed explanation of the usage of MySQL memory tables and temporary tables

Usage of MySQL memory tables and temporary tables...

Using JavaScript to implement carousel effects

This article shares the specific code for JavaScr...

Practical experience of implementing nginx to forward requests based on URL

Preface Because this is a distributed file system...

JavaScript implements constellation query function with detailed code

Table of contents 1. Title 2. Code 3. Results IV....

Summary of the use of MySQL date and time functions

This article is based on MySQL 8.0 This article i...

Detailed graphic explanation of sqlmap injection

Table of contents 1. We found that this website m...

Linux automatically deletes logs and example commands from n days ago

1. Delete file command: find the corresponding di...

Detailed explanation of angular parent-child component communication

Table of contents APIs used Simple Example person...

Several ways to implement image adaptive container with CSS (summary)

There is often a scenario where the image needs t...

mysql indexof function usage instructions

As shown below: LOCATE(substr,str) Returns the fi...

js to achieve the effect of dragging the slider

This article shares the specific code of how to d...

Detailed explanation of writing and using Makefile under Linux

Table of contents Makefile Makefile naming and ru...