Vaishnav Mhetre
Vaishnav Mhetre

Reputation: 199

Vue-Resource Authorization header unable to set

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:

  1. Vue @ 2.2.1
  2. Vue Resource @ 1.3.4
  3. Vue Router @ 2.6.0
  4. Laravel @ 5.4
  5. Laravel Passport @ 2.0

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 -

Auth Package code (setters and getters for token)

[ Image Desc: Auth Package code (setters and getters for token) ]

Sign in module snippet to set token on arrival -- **Works correctly**

[ 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

unauthorized without refresh

[ Image desc: unauthorized without refresh ] [without refresh, Vue.http.headers.common['Authorization'] shows "Bearer null"4

[ Image desc: without refresh, Vue.http.headers.common['Authorization'] shows "Bearer null" ]

But passes the token after refreshing the page...!

after refresh, the token is passed successfully [ 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

Answers (2)

Rohit Kapali
Rohit Kapali

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

Nucleus
Nucleus

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

Related Questions