Two ways of route interception for Vue authentication

Front end_ A stranger on the road 2020-11-09 23:49:04
ways route interception vue authentication

vue Two methods of authentication in

There are two kinds of authentication : One is route interception , One is dynamic routing .

Route blocking

adopt vue-router Of beforeEach Method to intercept every route access , Determine whether there are authentication requirements or authority verification in the intercepted information , In order to achieve Authentication .
If the permission is not enough , Although the access path exists, it will be blocked .

Dynamic routing

After logging in, according to the user information and permissions, dynamically add the correct authority routing , If the permission is not enough , There is no access path .


Routing interception is relatively simple to implement , Just save the user permission information when you log in , Then, when you write a route, you will add permission information to the route that needs authentication , And then in beforeEach In interception, judge whether processing can enter , also , Even if passed f5 Refresh the page ,
As long as the user information authority information is saved , Then authentication can be realized .

And dynamic routing , It's relatively difficult to implement , It may also require back-end cooperation , But it seems to be more advanced in terms of security , After all, even if you know that there is a certain permission to route , But I don't paint at all , You can never walk in . Dynamic routing requires logging user permissions after logging in
Menu list , This list may be given by the back end or summarized by the front end itself . If the front-end summarizes itself, it needs to generate different routing lists according to users with different permissions , Then after logging in, render on demand . Moreover, the conditions and implementation logic of this dynamic route loading judgment will be more complex
miscellaneous . You need to consider f5 After refresh, dynamic route reloads , Because you will not go through the login operation again at this time , So dynamic route loading will not be placed in the callback of login function , But it has to be rendered after landing , So we put it in the same way router Of beforeEach In this way , It's just
The judgment condition needs to be changed to that the user permission information already exists, but the dynamic route is loaded by rendering , For specific implementation, please see an example .

Example - Route blocking

// File directory
// webapp/src/routers/modules/user.js
// Routing can be differentiated by module , I've just refined , You can also put all routes in a folder , It's just that it might look a little bit more
const userRouter = [
{ path: '/user/router1', // In this way, loading on demand can be realized , Package and refine ,webpackChunkName It is the prefix of the file name generated by packaging
component: () => import(/* webpackChunkName: "router1" */ '@/pages/user/router1.vue'), meta: { // Put some custom information here ,permission It's access information , It will be later in beforeEach To judge , must amin To get into
// Sometimes we want to package all components under a certain route in the same asynchronous block (chunk) in . Just use name chunk, A special annotation syntax to provide chunk name ( need Webpack > 2.4).
// title: 'router1', permission: 'admin' } },{
path: '/user/router2', component: () => import(/* webpackChunkName: "router2" */ '@/pages/user/router2.vue'), meta: { title: 'router2' } }
export default userRouter;
// webapp/src/router/index.js
// Here we summarize all the detailed module routes
import Vue from 'vue';
import Router from 'vue-router';
import userRouter from '@/routers/modules/user.js';
// vue Use vue-router This plugin
const router = new Router({
routes: [ { path: '/', redirect: '/home' }, ...userRouter, { path: '*', redirect: '/404' } ]
export default router;
// webapp/src/main.js
// commonly router Of beforeEach Will be in main.js in , Throughout vue Load on instantiation .
import Vue from 'vue';
import router from '@/routers/index.js';
// It can be done here vue-router Of beforeEach Intercepted , You can put it somewhere else , I prefer to put this
router.beforeEach((to, from, next) => {
document.title = to.meta.title || ''; // Here we get the user information first , I'm lazy with sessionStorage Save
// It contains user rights , User information, etc
const user = JSON.parse(sessionStorage.getItem('ms_user')); // You have to add to.path !== 'login' The judgment of the , Or you'll fall into an infinite loop ,
// Because logic comes in for the first time , Judge that the user information does not exist , namely !user by true, Because of the use of next('/login') Instead of next(),
// It will enter the route jump again ,next() The method has no parameters, it goes directly to the page , Will not enter the route intercept again , If there are parameters, it will , Because of the jump ,
// So go into the route again , Judge again , Enter the route again , Judge again , Cycle, infinite cycle
// So it must be added to.path !== 'login' The judgment of the
if (!user && to.path !== '/login') { next('/login'); } else if (to.meta.permission) { user.permission === to.meta.permission ? next() : message.alert(' No authority ');
} else { next(); }});
new Vue({
router, render: h => h(App)

If you want to communicate, you can send a private message or wx:zilian_taoyaoyao

本文为[Front end_ A stranger on the road]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple