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.
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 })
}
})
Route::group(['middleware' => 'auth:api'], function() {
Route::get('/users', 'UsersController@users');
});
Laravel function
public function users(Request $request)
{
return $request->user();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With