授权标头不适用于http GET请求

时间:2018-05-02 10:58:20

标签: javascript vue.js vue-resource

我在我的项目中使用VueSession。我创建了一个登录组件,我将数据传递给我的后端(Django,返回JWT令牌)。这是我的问题。我的登录工作正常,它返回JWT,但当我想从其他端点获取数据时,我收到错误401(Authentication credentials were not provided)。当我在我的终端使用curl时,一切正常。

curl -X POST -d "username=test&password=test" http://localhost:8000/api/token/auth/ 它返回令牌

curl -H "Authorization: JWT <my_token>" http://localhost:8000/protected-url/ 它从网站返回数据

这是我在Vue项目中设置的内容。

Login.vue

<script>
import Vue from 'vue'

export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: ''
    }
  },

  methods: {
    login: function (username, password) {
      let user_obj = {
        "username": username,
        "password": password
      }
      this.$http.post('http://192.168.1.151:8000/api/token/auth', user_obj)
      .then((response) => {
        console.log(response.data)
        this.$session.start()
        this.$session.set('jwt', response.data.token)
        Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token

        // this.$router.push('/')

      })
      .catch((error_data) => {
        console.log(error_data)
      })
    }
  }
}
</script>

HereIWantUserGETRequest.vue

<script>
export default {
  data() {
    return {
      msg: "Welcome",
      my_list: []
    }
  },
  beforeCreate() {
    // IF SESSION DOESN'T EXIST
    if (!this.$session.exists()) {
      this.$router.push('/account/login')
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData: function() {
      this.$http.get('http://192.168.1.151:8000/api/user/data')
        .then((response) => {
          console.log(response.data)
          this.my_list = response.data
        })
        .catch((error_data) => {
          console.log(error_data)
        })
    }
  }
}
</script>

当然,我在main.js中设置了VueSession和VueResource

import VueSession from 'vue-session'
import VueResource from 'vue-resource'

Vue.use(VueResource)
Vue.use(VueSession)

3 个答案:

答案 0 :(得分:2)

修改

glTexImage2D()

Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token

希望它能帮到你

答案 1 :(得分:0)

您实际上并未将jwt令牌存储在浏览器中的任何位置(使用cookie或localStorage)。因此,Vue在内存中只有该页面的运行时(在单页应用程序的意义上)你已经请求你的jwt令牌。根据github docs of VueSession选项将令牌存储在你的浏览器中默认为false。只需将其设置为true即可:

#main.js

var options = {
  persist: true
}

Vue.use(VueSession, options)

我个人不使用这个库。我通常使用axios,Vuex和localStorage从头开始。这真的不是那么难,这个模式描述得很好here

答案 2 :(得分:0)

问题出在这一行Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token上。要修复它,我需要在我的main.js文件中:

if (this.$session.exists()) {
      var token = this.$session.get('jwt')
      console.log(token)
      Vue.http.headers.common['Authorization'] = 'JWT ' + token
}

现在它正在工作。

相关问题