[英]Authorization header doesn't work with http GET requests
我在项目中使用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)
编辑
Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token
与
Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token
希望对您有帮助
您实际上并没有将jwt令牌存储在浏览器中的任何位置(使用cookie或localStorage)。 因此,Vue仅在请求了jwt令牌的页面的运行时才在该内存中拥有令牌。根据VueSession的github文档,将令牌存储在浏览器中的选项是默认为false。 像这样将其设置为true:
#main.js
var options = {
persist: true
}
Vue.use(VueSession, options)
我个人不使用此库。 我通常使用axios,Vuex和localStorage从头开始。 确实没有那么困难, 这里对模式进行了很好的描述。
问题出在这行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
}
现在它正在工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.