Felipe Paz
Felipe Paz

Reputation: 357

Authentication with vuejs and laravel

Where have I to authenticate in a SPA application using laravel and vuejs? I'm developing a normal web application with laravel and blade. Nothing out of ordinary, but, now, I'm trying to make a spa application using laravel and vuejs - backend separeted from frontend. Where would I have to authenticate in this example? In php routes or vuejs routes or both? My laravel app, only laravel, it works as expected, user permissions, user session, a normal application but in vuejs, how I can do the same verifications as well?

Upvotes: 1

Views: 3406

Answers (1)

skribe
skribe

Reputation: 3615

Without knowing you exact Laravel authentication setup I would just say you authenticate through ajax at the same route as you do in Laravel. In a fairly standard setup using axios I do it like this.

      ajaxLogin(){
            axios.post('/login',{
                email: this.loginEmail,
                password: this.loginPassword
            }).then(function (res) {
                this.getCrsfToken(); //refresh crsf token
            }.bind(this));
      }

Notice the getCrsfToken function here. This may be necessary if your SPA (page) is not being refreshed when logging out and back in. Like in the case of the session expiring while the browser window is open. You would use something like the following to refresh the crsf token if you are including it the standard Laravel way in the header.

In your Routes or Controller

Route::get('/getToken', function(){
    return csrf_token();
})->middleware('auth');

In your Vue component

getCrsfToken(){
    axios.get('/getToken')
         .then(function(res){
               // Refresh crsf token from session after login
               window.axios.defaults.headers.common['X-CSRF-TOKEN'] = res.data;
          });  
 },

Upvotes: 1

Related Questions