vue-15 (实践练习:使用路由防护实现身份验证和授权)
实践:使用路由防护实现身份验证和授权
使用 Route Guard 实现身份验证和授权
身份验证和授权是现代 Web 应用程序的关键方面,确保只有授权用户才能访问应用程序的特定部分。Vue Router 提供了一个强大的机制,称为路由守卫来实现这些安全措施。路由守卫允许您根据特定条件控制对路由的访问,例如用户是否已登录或是否具有必要的权限。本章将深入探讨在 Vue.js 中使用路由守卫进行身份验证和授权的实际实现。
了解路由守卫
Route Guards 是导航到路由时执行的函数。它们可用于拦截导航并允许导航继续、重定向到其他路由或完全取消导航。路由守卫有三种类型:
- Global Guards: 这些守卫应用于应用程序中的所有 route。
- Per-Route Guards: 这些守卫应用于特定路由。
- In-Component Guards: 这些守卫在组件中定义,并在导航到该组件的路线或从该组件的路线导航时应用。
在本课中,我们将重点介绍全局守卫和每路由守卫,因为它们最常用于身份验证和授权。
全局守卫
全局守卫使用 router.beforeEach
、router.beforeResolve
和 router.afterEach
注册。beforeEach
守卫是最常用于身份验证和授权的。
例:
import { createRouter, createWebHistory } from 'vue-router';const routes = [{ path: '/', component: Home },{ path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },{ path: '/login', component: Login },
];const router = createRouter({history: createWebHistory(),routes,
});router.beforeEach((to, from, next) => {// Check if the route requires authenticationif (to.meta.requiresAuth) {// Check if the user is logged inif (localStorage.getItem('token')) {// User is logged in, proceed to the routenext();} else {// User is not logged in, redirect to the login pagenext('/login');}} else {// Route does not require authentication, proceednext();}
});export default router;
解释:
- 我们为
/dashboard
定义一个路由,并使用requiresAuth: true
添加一个meta
字段。这表示此路由需要身份验证。 - 在
router.beforeEach
守卫中,我们检查to
路由(被导航到的路由)是否将requiresAuth
元字段设置为true
。 - 如果是这样,我们通过检查
localStorage
中是否存在令牌来检查用户是否已登录。 - 如果用户已登录,我们调用
next()
以继续路由。 - 如果用户没有登录,我们调用
next('/login')
重定向到登录页面。 - 如果路由不需要身份验证,我们调用
next()
以继续路由。
每路由守卫
每个路由守卫是使用 beforeEnter
选项直接在路由配置中定义的。
例:
import { createRouter, createWebHistory } from 'vue-router';const routes = [{ path: '/', component: Home },{path: