vue-resource interceptor for auth headers

tam5 picture tam5 · Sep 23, 2016 · Viewed 21.4k times · Source

I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.

I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:

methods: {
    getUser () {
      this.$http.get('http://localhost:8000/api/user', 
      {
        headers: {
          'Authorization': 'Bearer eyJ0e.....etc',
          'Accept': 'application/json'
        }
      }).then((response) => {
        this.name = response.data.name
      });
    },

However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.

Based on the vue-resource readme I am trying this in my main.js:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})

And then back in my component I now just have:

this.$http.get('http://localhost:8000/api/user').then((response) => {
    this.name = response.data.name
});

Problem:

When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?

Edit: When I use dev-tools to view the outgoing requests I see the following behavior:

When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.

However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.

Answer

tam5 picture tam5 · Sep 23, 2016

It turns out my problem was the syntax for which I was setting the headers in the interceptor.

It should be like this:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
  request.headers.set('Accept', 'application/json')
  next()
})

While I was doing this:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})