Authentication in Laravel-Vue.js non-SPA Using Passport

Behrang Nour
May 18 · 6 min read

In a Nutshell

This tutorial will walk through the process of user authentication in Ajax requests sending by front end component in multi-page applications.

Resources: The following resources were used in this tutorial.

  • Laravel 5.8
  • Laravel Authentication
  • Laravel Passport
  • Vue.js 2
  • Axios

GitHub project link:

Defining The Problem

Assume in user profile page you want to show user’s information by Ajax call, so you need to create an endpoint in the back-end with these features:

  • Protecting endpoint from CSRF attacks
  • Allowing only authenticated users to access the endpoint
  • Retrieving the authenticated user from the request

Chapter 1: Installing and Configuring Laravel

If you have already installed Laravel you can skip this chapter.

Step 1: Install Laravel

For more information follow the whole instructions here:

We are using the Laravel latest release 5.8.17

Open up your console and run following command to create new project. I named it apiauth-tut.

composer create-project --prefer-dist laravel/laravel apiauth-tut

Step 2: Configure Database

  • Create a database for use with our application.
  • Open .env file in root of the project and enter your database information inside it.

Step 3: Bring up the Project

Run the following command in your terminal:

php artisan serve

After finished you will get a message: Laravel development server started: <http://127.0.0.1:8000>

This command will start a development server. Go to your browser and visit http://127.0.0.1:8000. If you went everything well you should be able to see your home page.


Chapter 2: Installing Laravel Authentication

Laravel has a nice authentication implementation.

There are two major area in the Laravel request life-cycle where authentication comes into play:

  • When a user attempts to log in
  • When a user attempts to access authenticated content

In the project root run next commands in a new terminal:

php artisan make:authphp artisan migrate

After refresh your page you will see Login and Register link in top right, now you can create a user account.


Chapter 3: Configuring JS and SASS and Vue.js

In this chapter we’re going to setup our application to compile assets, this gonna happen with installing Laravel Mix.

Laravel Mix provides a fluent API for defining webpack build steps for your application using several common CSS and JavaScript pre-processors.

Find complete information about it:

Step 1: Install The Dependencies

Before start, make sure that Node.js and NPM are installed on your machine.

Install the dependencies by running:

npm install

Step 2: Running Mix and Watching Assets For Changes

The npm run watch command will continue running in your terminal and watch all relevant files for changes. Webpack will then automatically recompile your assets when it detects a change so just run this command in a new terminal:

npm run watch

Chapter 4: Structuring Vue

We need to create a profile page to show users information.

Step 1: Create a Vue Component

1- Create a new Vue component file:

apiauth-tuth\resources\js\components\ProfileComponent.js

<template>
<div class="card">
<div class="card-header">User's Information</div>
<div class="card-body">
<div class="alert alert-success" role="alert">
{{ name }}
</div>
</div>
</div>
</template>

<script>
export default {

data() {
return {
name: ''
}
},

mounted() {
this.name = 'Behrang No';
}

}
</script>

As you can see for now I just show the user name statically, in the next step we will make it dynamic by getting data from our API

2- Register the component inside app.js

Inside apiauth-tuth\resources\js\app.js , register the component by adding this line:

Vue.component('profile-component', require('./components/ProfileComponent.vue').default);
Register the Vue component

Step 2: Change Home Page to Show Our Component

Open home page apiauth-tuth\resources\views\home.blade.php and add this block to show user information like this.

<!-- Profile -->
<div class="row justify-content-center mt-3">
<div class="col-md-8">
<profile-component></profile-component>
</div>
</div>
<!-- Profile End -->
Our final home page will be like this

Now just register a user name and go to your home page, you might see your home page like this:


Chapter 5: Creating API

We need to create a end point and get the information form it so let’s do it together.

Step 1: Create a end point

We just want to simply create an endpoint inside our API routers and not in controller to make it easy.

Open up \apiauth-tuth\routes\api.php and add these line at the end.

Route::get('/users', function (Request $request) {

return response()->json(['name' => 'Behrang No']);

});
Our api.php router file maybe something like this

Step 2: Change our Vue component to read data form our End Point

apiauth-tuth\resources\js\components\ProfileComponent.js

<template>
<div class="card">
<div class="card-header">User's Information</div>
<div class="card-body">
<div class="alert alert-success" role="alert">
{{ name }}
</div>
</div>
</div>
</template>

<script>
export default {

data() {
return {
name: ''
}
},

mounted() {
axios.get('/api/users')
.then(response => {
this.name = response.data.name;
});

}

}
</script>

If you refresh the page you will see the data coming from our end point but this endpoint is not secured yet, every one can read the data also it can not retrieve the authenticated user’s information by the incoming request.


Chapter 6: Securing Our End Point

Laravel Passport adds the capabilities as an server to your Laravel application, which manages how third party accessing to your application data.

Step 1: Install Laravel Passport

To get started, install it via Composer package management by running:

composer require laravel/passport
php artisan migrate
php artisan passport:install

After running these commands, add the Laravel\Passport\HasApiTokentrait to your App\User model.

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}

Next, you should call the Passport::routes method within the boot method of your AuthServiceProvider.

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];

/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();

Passport::routes();
}
}

Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.

'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

You may export the default migrations using

php artisan vendor:publish --tag=passport-migrations

Step 2: Consuming Your API With JavaScript

It took me some time to figure out this important part. Typically, if you want to consume your API from your JavaScript application, you would need to do this step to pass the access token to the application with each request to your application.

However, Passport includes a middleware that can handle this for you. All you need to do is add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:

'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

Step 3: Change Your End Point to return real user name

Lets change our end point and get user form the request.

<?php

use
Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});

Route::middleware('auth:api')->get('/users', function (Request $request) {

return response()->json(['name' => Auth::User()->name]);

});

Refresh the page and see the authenticated user name. For checking our end point against external request you can call the end point by rest client like and make sure it’s not working. So far you have connected your front end and back end authentication process.

The final result

Behrang Nour

Written by

Web developer using PHP, Laravel and Vue. I enjoy bringing ideas to life.