This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Hello, Hello, I am gray little ape, a super bug writing program ape!

Today, when I was working on a project of vue and Springboot interaction, I wanted to implement some operations based on the front end, only after login authentication can access some pages, so here is a summary of a solution to implement this feature.

First of all, how DO I determine if I’m logged in,

First, the solution

Since shiro+Jwt security framework is adopted in my Springboot background, a token will be fed back to the front end after login, and the front end will store the token. Therefore, I go to find whether there is a token in the browser. If there is a token in the browser, the login is successful. Relevant pages can be accessed;

If there is no token, there is no login and J jumps to the login page. To simplify things, I’ve encapsulated the validation process.

Note:The premise of using this method is that your front and back ends are authenticated with Shiro and tokens, and the front end stores the tokens returned by the server.

Let the browser store the token returned by the server

Let’s start by looking at how the tokens returned from the server side are stored in my front end page.

First, I wrapped a SET_TOKEN method in the index.js file under the store file, which was used to store the token to the browser, so that we could get our token locally each time by using localstorage.getitem (“token”). It also encapsulates a REMOVE_INFO method that clears 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: "",
        // The user's information can be retrieved directly from the browser
        token: localStorage.getItem("token"),
        // Deserialize
        userInfo: JSON.parse(sessionStorage.getItem("userInfo"))},mutations: {
        /** Similar to the set operation */
        // Assign the token value
        SET_TOKEN: (state, token) = > {
            state.token = token;
            // Stores information in the browser so that it remains when the browser closes
            localStorage.setItem("token", token);
        },
        // Assign a value to userinfo
        SET_USERINFO: (state, userInfo) = > {
            state.userInfo = userInfo;
            // The session is cleared each time the browser closes and regenerated after logging in again
            // Since sessionStorage can't store objects, store them as strings
            sessionStorage.setItem("userInfo".JSON.stringify(userInfo));
        },
        // Remove user information
        REMOVE_INFO: (state) = > {
            // All user information is left blank when removing user information
            state.token = "";
            state.userInfo = {};
            localStorage.setItem("token"."");
            sessionStorage.setItem("userInfo".JSON.stringify("")); }},getters: {
        /** Similar to get request */
        // Get user information
        getUser: state= > {
            returnstate.userInfo; }},actions: {},
    modules: {}})Copy the code

Set access permissions in the request

Since not all of our pages are accessible only at login time, we need to set access permissions for the pages that need to be logged in to.

In vue, we generally set the access route in the index.js file under the router. For the request route that needs to add login permission, we can add meta attribute to it and set a Boolean attribute requireAuth. Whether this property is true is used to determine whether login authentication is required.

For example, our BlogEdit page can only be accessed at Login time, and the Login page does not require Login permission.

/** * Route registry */

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


// Register 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, which indicates that the operation can be performed only after login
        meta: {
            requireAuth: true}},]const router = new VueRouter({
    mode: 'history'.base: process.env.BASE_URL,
    routes
})

export default router

Copy the code

This will be judged each time a BlogEdit page is requested.

4. Encapsulate login authentication

Now we need to write a method that validates the property we just set. So create a permission.js file in the SRC directory and wrap it in it.

Here's the idea:First we intercept the request, obtain the requireAuth parameter in the request, and if the parameter is true, obtain the token in the browser to verify the login status. If a token is present, the request is allowed. If no token is obtained, the login page is redirected.

Note:Const token = ocalstorage.getitem (“token”) if you are logging in based on another authentication, you can replace // with your local token const token = ocalstorage.getitem (“token”), but the idea is the same.

The code is as follows:

/** * Request login authentication, if no login, can not access the page, return to the login page */
import router from "./router";

// Route judgement login, according to the route configuration file parameters
router.beforeEach((to,from,next) = >{
    // Determine whether the route requires login permission
    / / record. Meta. RequireAuth is to get to carry the parameters in the request
    if (to.matched.some(record= > record.meta.requireAuth)){
        // Obtain the local token
        const token = localStorage.getItem("token")
        console.log("Display token---------- :" + token)

        // Check whether the current token exists, that is, the login token
        if (token){
            // If you point to the login page, do nothing
            if (to.path === "/login"){

            }else {
                // If it is not a login page and the token exists, permit the login
                next()
            }
        }else {
        // If the token does not exist
        // Go to login
            next({path:'/login'}}})else {
        // If login authentication is not required, access directly
        next()
    }
})
Copy the code
Finally, don't forget to import this page into mian.js.
// Import permission.js, and the user controls the front-end permission
import "./permission"
Copy the code

To summarize

The main operation is step 3 and step 4, as long as you set the login authentication parameters in the request route, and step 4 write the login interception authentication, and imported into the main.js file, it is ok!

At this point through the front-end authentication login interception completed.If you have different opinions or methods, please leave a comment or write to me to discuss! I am aAsh little apeAnd we’ll see you next time!