关于如何使用 JWT 处理 Vuejs 身份验证的简单高级概述

Simple high-level overview of how to handle Vuejs authentication with JWT

只需要一个关于如何构建它的高级概述。 我有一个 Authentication js 对象 (es6 class),它被实例化一次,并使用 JWT。

import { getRouteByName, getRouter } from 'appRouter'
import axios from 'axios'

let instance = null
class AppAuthentication {
  constructor (http, router, localStorage = window.localStorage) {
    if (!instance) {
      instance = this
      this.storage = localStorage
      this.http = http
      // this.router = router // but it will be undefined
      this.api = http.create({baseURL: someURL, headers: {'Authorization':
      'Bearer ' + this.token}})
      this.watchRoutes()
    }
    return instance
  }

  watchRoutes () {
    this.router.beforeEach((to, from, next) => {
      let login = 'Login'
      if (to.name !== login && this.isLoggedOut()) {
      return next(getRouteByName(login))
    }
    next()
  })
  }
  login (credentials) {
    return this.http.post(`${SOME_URL}/login`, credentials)
  }

  finishAuthentication (token) {
    this.setToken(token)
    this.router.replace('/')
  }
  logout () {...}
  set token (token) { ... }
  get token () { ... }
  get router: () => getRouter() // this sucks
  isLoggedIn () {...}
  isLoggedOut () {...}
}
export default new AppAuthentication(axios, router /*(here router will be undefined)*/ )

问题是对象在 Vue Router 之前实例化 "ready" 所以引用是未定义的。我有一个糟糕的 getter 可以返回到 vue 路由器。显然这不是最好的方法。

我在 reactJS 领域看到了高级组件,它们可以将内容包装在应用程序上。没见过这样的东西是 vue.通常执行此操作的高级方法是什么?

像这样的方法吗?

<app>
  <authentication>
    <some-tag></some-tag>
    <router-view></router-view>
  </authentication>
</app>

我不确定我是否完全理解您的身份验证对象。我建议使用 Vuex 来维护您的用户状态,而不是将其存储在本地存储中。您的 'get token' 可以是一个动作,您的 'set token' 可以是一个突变。您可以使用 Persisted State 将 Vuex 镜像到 localStorage。

这是我处理 JWT 令牌的方式:

1) 除登录外,所有路由调用都需要令牌。您在之前的路由器防护中执行此操作。所以如果使用 localStorage,在 routes.js 中是这样的:

router.beforeEach((to, from, next) => {
let now = new Date()
if (/login|reset|activate|forgot/.test(to.path.toLowerCase())) {
    next()
}
else if (localStorage.getItem('token') && localStorage.getItem('tokenExpires') > now){
    next()
}
else {
    next('/login')
}

2) 处理 403 或其他身份验证错误,以便它们路由到登录或您想要它去的任何地方。在我当前的应用程序中,我们将 GraphQL 与 Fetch 结合使用,并且所有请求都通过一个 GraphQL.js 文件,因此我们有一个简单的位置来处理处理请求的逻辑。

3) 处理登录组件本身的 api 调用,将响应发送到 Vuex 突变或将其存储在 local/session 存储中。

Vue 的一大好处是它的简单性。提示:如果可以,请将您不会在其他地方重用的相关功能放在组件本身上。它更直观,并使代码更易于维护。