Vue implements user login and token verification

Vue implements user login and token verification

In the case of complete separation of the front-end and back-end, the general idea of ​​implementing token verification in the Vue project is as follows:

1. When logging in for the first time, the front-end calls the back-end login interface and sends the username and password

2. The backend receives the request, verifies the username and password, and returns a token to the frontend if the verification is successful.

3. The front end gets the token, stores it in localStorage and vuex, and jumps to the routing page

4. Every time the front-end jumps to a route, it determines whether there is a token in localStorage. If not, it jumps to the login page. If yes, it jumps to the corresponding route page.

5. Every time you call the backend interface, you must add a token to the request header

6. The backend checks whether there is a token in the request header. If there is a token, it gets the token and verifies it. If the verification is successful, it returns data. If the verification fails (for example, the token expires), it returns 401. If there is no token in the request header, it also returns 401.

7. If the status code received by the front end is 401, clear the token information and jump to the login page

vue-cli builds a project and briefly explains what the front end needs to do:

1. The login interface is called successfully, and the token is stored in localStorage and vuex in the callback function

login.vue

<template>
  <div>
    <input type="text" v-model="loginForm.username" placeholder="Username"/>
    <input type="text" v-model="loginForm.password" placeholder="password"/>
    <button @click="login">Login</button>
  </div>
</template>
 
<script>
import { mapMutations } from 'vuex';
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      userToken: ''
    };
  },
 
  methods: {
    ...mapMutations(['changeLogin']),
    login() {
      let _this = this;
      if (this.loginForm.username === '' || this.loginForm.password === '') {
        alert('Account or password cannot be empty');
      } else {
        this.axios({
          method: 'post',
          url: '/user/login',
          data: _this.loginForm
        }).then(res => {
          console.log(res.data);
          _this.userToken = 'Bearer ' + res.data.data.body.token;
          // Save user token to vuex_this.changeLogin({ Authorization: _this.userToken });
          _this.$router.push('/home');
          alert('Login successful');
        }).catch(error => {
          alert('Account or password error');
          console.log(error);
        });
      }
    }
  }
};
</script> 

index.js in the store folder

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
 
const store = new Vuex.Store({
 
  state: {
    //Store token
    Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : ''
  },
 
  mutations:
    // Modify the token and store it in localStorage
    changeLogin (state, user) {
      state.Authorization = user.Authorization;
      localStorage.setItem('Authorization', user.Authorization);
    }
  }
});
 
export default store;

2. Routing Navigation Guard

index.js in the router folder

import Vue from 'vue';
import Router from 'vue-router';
import login from '@/components/login';
import home from '@/components/home';
 
Vue.use(Router);
 
const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/home',
      name: 'home',
      component: home
    }
  ]
});
 
// Navigation guard // Use router.beforeEach to register a global front guard to determine whether the user is logged in router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    let token = localStorage.getItem('Authorization');
 
    if (token === null || token === '') {
      next('/login');
    } else {
      next();
    }
  }
});
 
export default router;

3. Add token to request header

// Add a request interceptor and add a token to the request header
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('Authorization')) {
      config.headers.Authorization = localStorage.getItem('Authorization');
    }
 
    return config;
  },
  error => {
    return Promise.reject(error);
});

4. If the status code is 401, clear the token information and jump to the login page

localStorage.removeItem('Authorization');
this.$router.push('/login');

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • VUE implements token login verification
  • Vue implements login verification code
  • Vue login sliding verification implementation code
  • Use vue-route's beforeEach to implement navigation guard (verify login before route jump) function
  • Vue actual combat vue login verification implementation code
  • Vue login registration and token verification implementation code
  • How to implement the verification login status in Vue
  • vue router+vuex implements home page login verification logic
  • An example of Vue using the routing hook to jump to the login page after the token expires
  • Token verification login in Vue project (front-end part)

<<:  Tutorial on installing Ubuntu 20.04 and NVIDIA drivers

>>:  MySQL cross-table query and cross-table update

Recommend

Docker-compose one-click deployment of gitlab Chinese version method steps

1. Introduction to gitlab Gitlab official address...

Combining XML and CSS styles

student.xml <?xml version="1.0" enco...

How to use nginx to build a static resource server

Taking Windows as an example, Linux is actually t...

Quickly solve the problem that CentOS cannot access the Internet in VMware

Yesterday I installed CentOS7 under VMware. I wan...

MySQL foreign key (FOREIGN KEY) usage case detailed explanation

Introduction: The disadvantages of storing all da...

Use of js optional chaining operator

Preface The optional chaining operator (?.) allow...

Dockerfile implementation code when starting two processes in a docker container

I want to make a docker for cron scheduled tasks ...

How to use nginx to intercept specified URL requests through regular expressions

nginx server nginx is an excellent web server tha...

Solve the problem that the docker container cannot ping the external network

Today, when I was building a redis environment in...

HTML Tutorial: Collection of commonly used HTML tags (4)

These introduced HTML tags do not necessarily ful...

Vue implements verification code countdown button

This article example shares the specific code of ...

Detailed explanation of several ways to install CMake on Ubuntu

apt install CMake sudo apt install cmake This met...

How to set focus on HTML elements

Copy code The code is as follows: <body <fo...