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

Behrang Nour
May 18, 2019 · 6 min read
Image for post
Image for post

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.

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

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:

  • 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: Installation Laravel The PHP Framework For Web Artisans

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
Image for post
Image for post

Chapter 2: Installing Laravel Authentication

Laravel has a nice authentication implementation.

  • When a user attempts to access authenticated content
php artisan make:authphp artisan migrate
Image for post
Image for post

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.

Step 1: Install The Dependencies

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

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:

<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>
Vue.component('profile-component', require('./components/ProfileComponent.vue').default);
Image for post
Image for post
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 -->
Image for post
Image for post
Our final home page will be like this
Image for post
Image for post

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.

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

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

});
Image for post
Image for post
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>

Chapter 6: Securing Our End Point

Laravel Passport adds the capabilities as an OAuth2 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
<?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;
}
<?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();
}
}
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

Step 2: Consuming Your API With JavaScript

'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]);

});
Image for post
Image for post
The final result

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store