Detailed implementation of Vue dynamic permission login: dynamic permission control based on routing and roles

When implementing a web application, it is usually necessary to control the permissions of different users to ensure the security and stability of the system. For the permission control of Vue applications, we can implement dynamic permission control based on routing and roles.

This article will introduce in detail how to implement user dynamic permission login based on the Vue framework, and will help readers understand the principle and steps of this function more deeply through sample codes and diagrams.

Part 1: Understanding the concept of dynamic permission login

Dynamic permission login, also known as role permission control, refers to a permission management method that controls the system resources that users can access according to their role information. When implementing dynamic permission login, we need to set different roles for different users in the system, and correspond these roles to resources in the system. When a user logs in to the system, the system will control the resources that the user can access according to the user's role to ensure the security and stability of the system.

In a Vue application, we usually control the pages that users can access through routing, and the access rights of routing can be controlled by the user's role. Therefore, the core of implementing dynamic permission login is to dynamically control routing.

Part 2: The mapping relationship between routes and roles

In the process of implementing dynamic permission login, we need to map routes to roles. Specifically, we need to add a meta field in the route configuration to store the role information required by the route. The sample code is as follows:

const routes = [
  {
    
    
    path: '/admin',
    name: 'admin',
    component: Admin,
    meta: {
    
    
      roles: ['admin']
    }
  },
  {
    
    
    path: '/user',
    name: 'user',
    component: User,
    meta: {
    
    
      roles: ['admin', 'user']
    }
  }
]

In the above code, we added meta fields to the two routes and stored the required role information in the roles attribute. Among them, the /admin route requires the admin role to access, while the /user route requires both admin and user roles to access.

Part Three: Permission Control in Vue Components

In the Vue component, we can realize the dynamic permission control of the user through the role information in the routing meta information. Specifically, we can use Vue Router's global front guard beforeEach() to determine the user's role information before the user accesses the route, so as to control the access rights of the route. The sample code is as follows:

router.beforeEach((to, from, next) => {
    
    
  const roles = to.meta.roles
  const role = getUserRole() // 获取用户角色信息
  if (roles && roles.indexOf(role) === -1) {
    
    
    // 用户没有该路由需要的角色,禁止访问
    next('/403')
  } else {
    
    
    // 用户具有该路由需要的角色,可以访问
    next()
  }
})

In the above code, we obtained the role information of the route to be accessed in the global pre-guard, and obtained the role information of the current user through the getUserRole() function. If the current user does not have the roles required by the route, we will disable their access and redirect to a 403 page; otherwise, we will allow them to access the route.

Part 4: Realize dynamic permission login with Vuex

When implementing dynamic permission login, we can use Vuex to manage the user's login status and role information. We can store the token and role information of the user after login in Vuex, and obtain the current user's role information through the getter function in Vuex. The sample code is as follows:

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    
    
  state: {
    
    
    token: '',
    roles: []
  },
  mutations: {
    
    
    SET_TOKEN: (state, token) => {
    
    
      state.token = token
    },
    SET_ROLES: (state, roles) => {
    
    
      state.roles = roles
    }
  },
  getters: {
    
    
    getUserRole: state => {
    
    
      return state.roles[0] || ''
    }
  }
})

export default store

In the above code, we use Vuex to manage the user's login status and role information. We define two states of token and roles in the state, which respectively represent the token and role information after the user logs in. In mutations, we define two mutations, SET_TOKEN and SET_ROLES, for setting token and role information. In the getter, we define the getUserRole function to obtain the role information of the current user.

Part V: Demonstration with Examples

We will demonstrate the implementation of dynamic permission login through a simple example. In this example, we will implement a routing authority control system based on role control, and help readers understand the principle and steps of this function more deeply through sample codes and diagrams.

First, we need to install Vue Router and Vuex, and the axios library for requesting login information from the backend. The sample code is as follows:

npm install vue-router vuex axios -S

After installing the dependencies, we need to configure Vue Router and Vuex, and define a simple login page and an administrator page. The sample code is as follows:

<!-- Login.vue -->
<template>
  <div>
    <h1>用户登录</h1>
    <form>
      <label>用户名:<input v-model="username"></label>
      <label>密码:<input type="password" v-model="password"></label>
      <button type="submit" @click.prevent="login">登录</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    login () {
      axios.post('/api/login', {
        username: this.username,
        password: this.password
      }).then(response => {
        const { token, roles } = response.data
        this.$store.commit('SET_TOKEN', token)
        this.$store.commit('SET_ROLES', roles)
        this.$router.push('/')
      }).catch(error => {
        console.error(error)
      })
    }
  }
}
</script>
<!-- Admin.vue -->
<template>
  <div>
    <h1>管理员页面</h1>
    <p v-if="isUserAdmin">您是管理员,可以访问这个页面</p>
    <p v-else>您不是管理员,无法访问这个页面</p>
  </div>
</template>

<script>
export default {
  computed: {
    isUserAdmin () {
      return this.$store.getters.getUserRole === 'admin'
    }
  }
}
</script>

In the above code, we use the axios library to send a request to the backend and get the login information. After successfully obtaining the login information, we store the token and roles in Vuex, and jump to the system homepage through the $router.push() function. In the Admin.vue component, we use the computed attribute to obtain the role information of the current user to control user access rights.

Finally, we need to configure Vue Router and Vuex in the main.js entry file, and introduce the Login.vue and Admin.vue components. The sample code is as follows:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
    
    
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Part VI: Summary and Reflections

Through the introduction of this article, we understand the concept and implementation steps of dynamic permission login, and demonstrate how to implement user dynamic permission login based on routing and role information through sample code. When implementing dynamic permission login, we need to map routes to roles, and use Vue Router's global front guard to control user access rights. At the same time, we also use Vuex to manage user login status and role information.

In actual projects, we can further optimize the implementation of dynamic permission login according to actual needs to meet the security and stability requirements of the project. At the same time, we also need to pay attention to the maintainability and reusability of the code, so that it can be more conveniently modified and optimized in the later project maintenance.

Guess you like

Origin blog.csdn.net/canshanyin/article/details/130958807