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

CnBlogs custom blog style sharing

After spending half the night on it, I finally ma...

A brief discussion on Linux signal mechanism

Table of contents 1. Signal List 1.1. Real-time s...

MySQL 5.7 cluster configuration steps

Table of contents 1. Modify the my.cnf file of se...

Vue implements anchor positioning function

This article example shares the specific code of ...

How to implement Docker to dynamically pass parameters to Springboot projects

background Recently, some friends who are new to ...

Analysis of pitfalls in rounding operation of ROUND function in MySQL

This article uses examples to illustrate the pitf...

A simple explanation of MySQL parallel replication

1. Background of Parallel Replication First of al...

A brief discussion on using Vue to complete the mobile apk project

Table of contents Basic Configuration Entry file ...

Explanation of the concept and usage of Like in MySQL

Like means "like" in Chinese, but when ...

How to build php7 with docker custom image

First, perform a simple Docker installation. To c...