Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API - Authentication works just after reloading the page

I am trying to build a Single Page Application (SPA) using VueJS as a front-end and Laravel as a back-end.
I am using laravel's passport to manage the authentication tokens etc.


The problem: After login I have to reload the page to be successfully authenticated.


Login method
data() {
   return {
       email: '',
       password: '',
   }
},
methods: {
   login() {
       var data = {
           client_id: 2,
           client_secret: '****************************',
           grant_type: 'password',
           username: this.email,
           password: this.password
       }
       // send data
       this.$http.post('oauth/token', data)
          .then(response => {
               // authenticate the user
               this.$store.dispatch({
                   type: 'authenticate',
                   token: response.body.access_token,
                   expiration: response.body.expires_in + Date.now()
               })
               // redirect after successful login
               if (this.$route.query.from)
                    this.$router.push(this.$route.query.from)
               else
                    this.$router.push('/feed')
               })
        }
    }

Get the user information from the backend (just works after refreshing the page)

setUser () {
     // this route throws 'unauthenticated' error 
     // and works only after refreshing the page
     this.$http.get('api/users/') 
          .then(response => {
              this.$store.dispatch({
                   type: 'setUser',
                   id: response.body.id,
                   email: response.body.email,
                   name: response.body.name
               })
          })
     }
}

Vuex store

export default new Vuex.Store({
    state: {
        isAuth: !!localStorage.getItem('token'),
        user: {
            id: localStorage.getItem('id'),
            email: localStorage.getItem('email'),
            name: localStorage.getItem('name')
        }
    },
    getters: {
        isLoggedIn(state) {
            return state.isAuth
        },
        getUser(state) {
            return state.user
        }
    },
    mutations: {
        authenticate(state, { token, expiration }) {
            localStorage.setItem('token', token)
            localStorage.setItem('expiration', expiration)
            state.isAuth = true
        },
        setUser(state, { id, email, name }) {
            localStorage.setItem('id', id)
            localStorage.setItem('email', email)
            localStorage.setItem('name', name)
            state.user.id = id
            state.user.email = email
            state.user.name = name
        }
    },
    actions: {
        authenticate: ({ commit }, { token, expiration }) => commit('authenticate', { token, expiration }),
        setUser: ({ commit }, { id, email, name }) => commit('setUser', { id, email, name })
    }
})


Laravel route
Route::group(['middleware' => 'auth:api'], function() {
    Route::get('/users', 'UsersController@users');
});

Laravel function

public function users(Request $request)
{
   return $request->user();
}


The error message

enter image description here
When I reload the page the error message disappears and I am successfully authenticated.


I would be very happy for any kind of help!
like image 689
Schwesi Avatar asked Sep 08 '17 09:09

Schwesi


1 Answers

Thanks to Frank Provost I figured out the answer. In case anybody else comes across the same problem:

I was not passing the token with every request.

I had to change this

Vue.http.headers.common['Authorization'] = 'Bearer ' + Vue.auth.getToken()

to this

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

Now, everything works as expected - no need to refresh the url.

like image 113
Schwesi Avatar answered Nov 09 '22 12:11

Schwesi