【问题标题】:How to store, manage REST API JWT authentication token in vue?如何在 vue 中存储、管理 REST API JWT 身份验证令牌?
【发布时间】:2019-11-29 05:40:44
【问题描述】:

我是一个菜鸟,使用 vue.js 和节点身份验证 api,该 api 工作正常并在响应中提供 jwt 令牌,我的问题是如何在随后的所有请求中使用令牌(使用 axios) ,以及任何在前端处理令牌的最佳实践。

谢谢

【问题讨论】:

  • 您应该将令牌保存在本地存储中并随每个请求一起发送
  • 展示你的作品?
  • methods: { login(e) { e.preventDefault() let currentObj = this this.axios.post('http://localhost:3600/auth', { email: this.email, password: this.password }) .then(function (response) { // how to store the token after this??? currentObj.output = response.data console.log(currentObj.output) }) .catch(function (error) { currentObj.output = error console.log(currentObj.output) }) } }

标签: javascript node.js vue.js jwt axios


【解决方案1】:

您可以在您的 vuejs 应用程序中为您的场景使用类似的东西。

import axios from 'axios'

const API_URL = 'http://localhost:3000'

const securedAxiosInstance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

const plainAxiosInstance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

securedAxiosInstance.interceptors.request.use(config => {
  const method = config.method.toUpperCase()
  if (method !== 'OPTIONS' && method !== 'GET') {
    config.headers = {
      ...config.headers,
      'X-CSRF-TOKEN': localStorage.csrf
    }
  }
  return config
})

securedAxiosInstance.interceptors.response.use(null, error => {
  if (
    error.response &&
    error.response.config &&
    error.response.status === 401
  ) {
    return plainAxiosInstance
      .post('/refresh', {}, { headers: { 'X-CSRF-TOKEN': localStorage.csrf } })
      .then(response => {
        localStorage.csrf = response.data.csrf
        localStorage.signedIn = true

        let retryConfig = error.response.config
        retryConfig.headers['X-CSRF-TOKEN'] = localStorage.csrf
        return plainAxiosInstance.request(retryConfig)
      })
      .catch(error => {
        delete localStorage.csrf
        delete localStorage.signedIn

        location.replace('/')
        return Promise.reject(error)
      })
  } else {
    return Promise.reject(error)
  }
})

export { securedAxiosInstance, plainAxiosInstance }

在您的组件中,您可以使用它来处理您的 api 请求

Products.vue

export default {
  name: 'products',
  data () {
    return {
      products: [],
      newProduct: [],
      error: '',
      editedProduct: ''
    }
  },
  created () {
    if (!localStorage.signedIn) {
      this.$router.replace('/')
    } else {
      this.$http.secured.get('/api/v1/products')
        .then(response => { this.products = response.data })
        .catch(error => this.setError(error, 'Something went wrong'))
    }
  },
  methods: {
    setError (error, text) {
      this.error = (error.response && error.response.data && error.response.data.error) || text
    },
    addProduct () {
      const value = this.newProduct
      if (!value) {
        return
      }
      this.$http.secured.post('/api/v1/products/', { product: { name: this.newProduct.name } })
        .then(response => {
          this.products.push(response.data)
          this.newProduct = ''
        })
        .catch(error => this.setError(error, 'Cannot create product'))
    },
    removeProduct (product) {
      this.$http.secured.delete(`/api/v1/products/${product.id}`)
        .then(response => {
          this.products.splice(this.products.indexOf(product), 1)
        })
        .catch(error => this.setError(error, 'Cannot delete product'))
    },
    editProduct (product) {
      this.editedproduct = product
    },
    updateProduct (product) {
      this.editedProduct = ''
      this.$http.secured.patch(`/api/v1/products/${product.id}`, { product: { title: product.name } })
        .catch(error => this.setError(error, 'Cannot update product'))
    }
  }
}

【讨论】:

    【解决方案2】:

    您可以找到here 很多我个人在项目中使用的好模式以及 JWT 令牌处理方式。

    要在浏览器中保存令牌,您可以使用 cookie、sessionStorage 或 localStorate,最后一个是现在最流行的(简短说明here)。

    简而言之,您可以创建一个 axion 实例并在发送请求之前添加一个令牌。

    const http = axios.create({
      baseURL: process.env.VUE_APP_SERVER_API,
      // here you can specify other params 
    })
    
    http.interceptors.request.use(request => {
      // Do something before request is sent
      request.headers['Authorization'] = `JWT ${TOKEN_HERE}`
      // some logic what to do if toke invalid, etc ...
      return request
    }, function (error) {
      // Do something with request error
      return Promise.reject(error)
    })
    

    【讨论】:

    • 那么 localStorage 可以使用吗?,我发现一些帖子说 otherwsie
    • 是的,这很正常。有时使用 sessionStorage 会更好,这取决于您的情况。
    • ${TOKEN_HERE} 来自哪里?
    猜你喜欢
    • 2016-08-10
    • 2019-02-27
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2016-03-24
    • 2021-05-22
    • 2020-09-12
    相关资源
    最近更新 更多