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

时间:2017-08-25 02:27:25

标签: vuejs2 jwt router

只需要对如何构建这个的高级概述。 我有一个Authentication js对象(es6类),它实例化一次,并使用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“准备好”之前实例化的,因此引用是未定义的。我有一个蹩脚的吸气剂,可以回到vue路由器。显然,这不是最好的方式。

我已经看到reactJS中的高级组件会将内容包装在应用程序上。没有看到这样的东西是vue。一般来说,高级别的方法是什么?

这样做的方法是什么?

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

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解您拥有的身份验证对象。我建议使用Vuex来维护用户状态,而不是将其存储在本地存储中。你的“获取令牌”可以是一个动作而你的“设置令牌”是一个突变。您可以使用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或其他身份验证错误,以便他们路由到登录或您想要的任何地方。在我当前的应用程序中,我们使用带有Fetch的GraphQL,并且所有请求都通过一个GraphQL.js文件,因此我们有一个简单的位置用于处理请求的逻辑。

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

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