Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the privilege Control of background Management system in vue

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

The knowledge of this article "how to achieve access control of the background management system in vue" is not quite understood by most people, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve access control of the background management system in vue" article.

I. Preface

In the advertising ji project, the rights management of roles is a difficult point that has been stuck for a long time. First of all, the permission control we have determined is divided into two parts, which are divided into more details according to the size of the grain:

Access control of interface

Permission control of the page

Whether the page in the menu can be accessed

Whether the permission control of the buttons (add, delete, change) on the page is displayed

Let's take a look at how these permission controls are implemented.

Second, access control of interface

The permission of the interface is the verification of the user. Normally, the server needs to return a Token to the foreground when the user logs in, and then the server needs to bring this Token to the foreground every time the interface is called.

Then the server gets the Token and compares it, and if it passes, it can access it.

The existing practice is to store the Token returned by the backend directly to the sessionStorage in the callback of a successful login, and then retrieve the Token and transfer it to the backend in headers upon request. The code is as follows:

This.$http ({method: 'get', url:' test/query?id=20', withCredentials: true, headers: {token: sessionStorage.getItem ('token'), name: sessionStorage.getItem (' name') / / username passed on the backend demand}}) .then (response = > operation after successful request}) copy the code

Later, in some articles, it was found that axios can plug Token directly into config.headers.Authorization in the interceptor as global input. Here is the code section:

/ / main.jsimport axios from 'axios'// instantiates Axios and sets the timeout const service = axios.create ({timeout: 5000}) / / baseURL// axios.defaults.baseURL =' https://api.github.com';// http request interceptor / / each request adds an Authorization field to the http header with the content of tokenservice.interceptors.request.use (config = > {if (store.state.user.token) {config.headers.Authorization = `token ${store.state.user.token} `) } return config}, err = > {return Promise.reject (err)}); export default service copy code

Third, page permission control

As mentioned earlier, there are two types of page permission control:

Whether the page in the menu can be accessed

Whether the permission control of the buttons (add, delete, change) on the page is displayed

These permissions are generally configured on a fixed page and recorded in the database after being saved.

Button permissions aside, page access permissions can be divided into two ways:

Displays all menus, prompting insufficient permissions when users access menus that are not within their own permissions

Only the within-permission menu that can be accessed by the current user is displayed. If the user is forced to access it through URL, it will go directly to 404.

Since it can't be clicked after it is shown, how many meanings is it? why don't you tease me? The so-called out of sight is net, after comprehensive consideration, it must be that the second plan is more in line with a good user experience.

Okay, let's take a look at the general process of page access:

After combing the process, we begin to write it in detail.

1. Create a routing table

It's not really difficult to create a routing table, just write it according to the example given in the vue-router official documentation. But because there are some pages that do not require access.

So you need to write login, 404, maintenance and other pages to the default route, and other pages that require permissions to a variable or a file, so that you can

In order to effectively reduce the follow-up maintenance pressure.

The code of index.js will be pasted below, and asynchronous routing will be reduced to avoid taking up too much space.

/ / router/index.jsimport Vue from 'vue'import Router from' vue-router'import App from'@ / App'import store from'.. / store/index'Vue.use (Router); / / the whitelist of manually redirected pages const whiteList = ['/'] / / pages that do not require permission by default const constantRouterMap = [{path:'/', name: 'login', component: (resolve) = > require (['@ / components/login'], resolve)}, {path: / index', name: 'nav.Home', component: (resolve) = > require ([' @ / components/index'], resolve)}, {path:'/ templateMake', name: 'template making' Component: (resolve) = > require (['@ / components/Template/templateMake'], resolve)}, {path:'/ programMack', name: 'programming', component: (resolve) = > require (['@ / components/Template/programMack'], resolve)}, {path:'/ release', name: 'program release', component: (resolve) = > require (['@ / components/Program/release'] Resolve)}] / / registered route export const router = new Router ({routes: constantRouterMap}) / / Asynchronous routing (pages requiring permissions) export const asyncRouterMap = [{path:'/ resource', name: 'nav.Resource', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Resource/resource'], resolve)}, {path:'/ template', name: 'nav.Template', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Template/template']) Resolve)}, {path:'/ generalSet', name: 'nav.System', meta: {permission: []}, component: (resolve) = > require ([' @ / components/SystemSet/generalSet'], resolve)}, {path:', name: 'nav.Log', component: App, children: [{path:' / userLog', name: 'nav.UserLog', meta: {permission: []} Component: (resolve) = > require (['@ / components/Log/userLog'], resolve),}, {path:'/ operatingLog', name: 'nav.SystemLog', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Log/operatingLog'], resolve),},]] Copy the code

Note: there is a very important thing to note here is that 404 pages must be loaded last. If you declare 404 pages together in constantRouterMap, all subsequent pages will be blocked to 404. For more information, please see addRoutes when you've got a wildcard route for 404s does not work.

2. Page access permissions

At the beginning, we combed through a general process of page access rights. Let's first implement the core part:

Let's first get the list of user permissions. Here we will touch on vuex status management. The official documents are described in detail, so we will not describe too much here. Please see the code below:

/ / store/index.jsimport Axios from 'axios'import Vue from' vue'import Vuex from 'vuex'Vue.use (Vuex); const axios = Axios.create (); const state = {mode:' login', list: []}; const getters = {}; const mutations = {setMode: (state, data) = > {state.mode = data}, setList: (state, data) = > {state.list = data}} Const actions = {/ / get permission list getPermission ({commit}) {return new Promise ((resolve, reject) = > {axios ({url:'/ privilege/queryPrivilege?id=' + sessionStorage.getItem ('privId'), methods:' get', headers: {token: sessionStorage.getItem ('token'), name: sessionStorage.getItem (' name')}}). Then ((res) = > {/ / Storage permission list commit ('setList', res.data.cust.privileges [0] .children) Resolve (res.data.cust.privileges [0] .children)}. Catch (() = > {reject ()}}; export default new Vuex.Store ({state, mutations, actions, getters}) copy the code

OK, we now request the backend to get the permission data and store the data in vuex. Next, we need to use the asynchronous routing table written before the returned data is matched, and combine the matching result with the static routing table to create the final actual routing table.

The most important of these is to take advantage of a new addRoutes method added in the vue-router2.2.0 version. Let's see how the official documentation explains this method:

Router.addRoutes (routes) 2.2.0 + dynamically add more routing rules. The parameter must be an array that meets the requirements of the routes option.

Then we can start using addRoutes for route matching now. Let's look at the code:

/ / router/index.js/** * match routes according to permissions * @ param {array} permission permission list (menu list) * @ param {array} asyncRouter Asynchronous routing object * / function routerMatch (permission, asyncRouter) {return new Promise ((resolve) = > {const routers = [] / / create route function createRouter (permission) {/ / add the router object matched to the path to the routers permission.forEach ((item) = > {if (item.children & & item.children.length) {createRouter (item.children)} let path = item.path) / / cyclic asynchronous routing, adding routes that match the permission list to routers asyncRouter.find ((s) = > {if (s.path = ='') {s.children.find ((y) = > {if (y.path = path) {y.meta.permission = item.permission; routers.push (s);}})} if (s.path = = path) {s.meta.permission = item.permission; routers.push (s) }})})} createRouter (permission) resolve ([routers])})} copy code

And then we write navigation hooks.

/ / router/index.jsrouter.beforeEach ((to, form, next) = > {if (sessionStorage.getItem ('token')) {if (to.path =' /') {router.replace ('/ index')} else {console.log (store.state.list.length) If (store.state.list.length = 0) {/ / if there is no permission list, it will request store.dispatch ('getPermission') .then again (res = > {/ / call the method routerMatch (res, asyncRouterMap) that matches the permission. Then (res = > {/ / addRoutes router.addRoutes the matching permission list (res [0])) Next ({... to, replace: true}). Catch (() = > {router.replace ('/')})} else {if (to.matched.length) {next ()} else {router.replace ('/')} else {if (whiteList.indexOf (to.path) > = 0) {next ()} else {router.replace ('/')}}); copy the code

Now that we have completed the access control of the page, let's explain the permissions of the operation button.

IV. Data operation authority

If you still remember the extra code we added in the previous routing configuration, let's take a look at it:

/ / Asynchronous routing (pages requiring permissions) export const asyncRouterMap = [{path:'/ resource', name: 'nav.Resource', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Resource/resource'], resolve)}, {path:'/ template', name: 'nav.Template', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Template/template']) Resolve)}, {path:'/ generalSet', name: 'nav.System', meta: {permission: []}, component: (resolve) = > require ([' @ / components/SystemSet/generalSet'], resolve)}, {path:', name: 'nav.Log', component: App, children: [{path:' / userLog', name: 'nav.UserLog', meta: {permission: []} Component: (resolve) = > require (['@ / components/Log/userLog'], resolve),}, {path:'/ operatingLog', name: 'nav.SystemLog', meta: {permission: []}, component: (resolve) = > require ([' @ / components/Log/operatingLog'], resolve),},]] Copy the code

Add a meta field for each routing page. Assign the matching detailed permission field here in the routerMatch function. You will get this field in the route object of each page.

AsyncRouter.find ((s) = > {if (s.path = ='') {s.children.find ((y) = > {if (y.path = path) {/ / assign y.meta.permission = item.permission; routers.push (s);}})} if (s.path = path) {s.meta.permission = item.permission; routers.push (s);}}) copy the code

Next, we write a vue custom instruction to judge the elements in the page that need to be authenticated, such as something like this:

/ * 3 represents an ID with upload permission, and 3 of the permissions display buttons * / copy code

We directly register a global directive and use vnode to access the vue method. The code is as follows:

/ / main.js// button permission instruction Vue.directive ('allow', {inserted: (el, binding, vnode) = > {let permissionList = vnode.context.$route.meta.permission; if (! permissionList.includes (binding.value)) {el [XSS _ clean] .removeChild (el)}}) copy the code

At this point, the access control process is completely over. In the end, let's take a look at the complete access control flow chart.

5. Complete flow chart of routing control

The above is about the content of this article on "how to realize the permission control of the background management system in vue". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report