Reputation: 199
Unable to set authorization header to "Bearer (token)" in main.js file after Sign In, shows 401 unauthorized but the headers are set after refresh while accessing files list from server
Detailed Description:
Specs:
Details:
I use "Sign In" module to sign in and store access and refresh tokens and expiration in local storage using an Auth package as follows -
[ Image Desc: Auth Package code (setters and getters for token) ]
[ Image desc: Sign in module snippet to set token on arrival -- Works correctly ]
As shown above, the route goes to 'dash', which loads files module but fails to fetch data from https://localhost:8000/api/files
[ Image desc: unauthorized without refresh ]
[4
[ Image desc: without refresh, Vue.http.headers.common['Authorization'] shows "Bearer null" ]
But passes the token after refreshing the page...!
[ Imag desc: after refresh, the token is passed successfully ]
And keeps on working until I don't refresh on sign in page after signing out and sign in again.
Any solutions will be appreciated.
Upvotes: 1
Views: 2342
Reputation: 216
You need to intercept each http
request and add the Authorization
header to the request in the main.js
file, for example
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer ' + Vue.auth.getAccessToken())
next()
})
Upvotes: 3
Reputation: 397
Set your header common after you set your token and expiration, this allows you to set your header upon login.
setToken(){
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.getToken();
}
Upvotes: 0