当前位置:首页 > VUE

vue路由实现jwt

2026-02-19 11:48:01VUE

Vue 路由实现 JWT 认证

安装依赖

确保项目中已安装 vue-router 和用于 JWT 处理的库(如 jsonwebtokenjwt-decode)。通过以下命令安装:

npm install vue-router jwt-decode

配置路由守卫

router/index.js 中设置全局前置守卫,拦截路由跳转并验证 JWT:

import Vue from 'vue'
import Router from 'vue-router'
import jwt_decode from 'jwt-decode'

Vue.use(Router)

const router = new Router({
  routes: [...]
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('jwt_token')
  const isAuthRequired = to.matched.some(route => route.meta.requiresAuth)

  if (isAuthRequired) {
    if (token) {
      try {
        const decoded = jwt_decode(token)
        const isExpired = decoded.exp < Date.now() / 1000
        isExpired ? next('/login') : next()
      } catch (error) {
        next('/login')
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router

路由元信息配置

在路由定义中标记需要认证的页面:

{
  path: '/dashboard',
  component: Dashboard,
  meta: { requiresAuth: true }
}

登录逻辑

在登录页面中,成功获取 JWT 后存储至本地并跳转:

methods: {
  async handleLogin() {
    const res = await api.login(this.credentials)
    localStorage.setItem('jwt_token', res.data.token)
    this.$router.push('/dashboard')
  }
}

请求拦截

axios 拦截器中自动附加 JWT:

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('jwt_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

退出处理

清除本地存储的 JWT 并重定向:

vue路由实现jwt

methods: {
  logout() {
    localStorage.removeItem('jwt_token')
    this.$router.push('/login')
  }
}

注意事项

  • JWT 应存储在 HttpOnly Cookie 或 localStorage 中,但需注意 XSS 风险
  • 敏感路由需服务端二次验证 JWT
  • 定期检查 JWT 过期时间并刷新令牌

标签: 路由vue
分享给朋友:

相关文章

vue怎么实现文件树

vue怎么实现文件树

Vue 实现文件树的方法 使用递归组件 递归组件是处理嵌套数据结构的理想方式。文件树通常包含文件夹和文件的嵌套结构,适合用递归组件实现。 <template> <ul>…

vue实现grid

vue实现grid

Vue 实现 Grid 布局的方法 使用 CSS Grid 布局 Vue 可以结合 CSS Grid 布局实现灵活的网格系统。CSS Grid 是现代浏览器原生支持的布局方案,无需额外依赖库。 &l…

vue实现颜色

vue实现颜色

Vue 实现颜色的方法 在 Vue 中实现颜色管理可以通过多种方式,以下是一些常见的方法: 使用 CSS 变量动态绑定颜色 在 Vue 组件的样式中定义 CSS 变量,并通过 Vue 的数据绑定动态…

vue实现全屏

vue实现全屏

Vue 实现全屏功能的方法 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 来实现。以下是几种常见的实现方式: 使用原生 Fullscreen API 通过调用 doc…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template>…