API Driven Development With Laravel and VueJS (Part 3 of 38)

Installing and Configuring Laravel Passport

Dan Pastori

September 25th, 2017

Laravel Passport was introduced in Laravel 5.3 and uses PHP League's oAuth2 server GitHub - thephpleague/oauth2-server: A spec compliant, secure by default PHP OAuth 2.0 Server. If you haven't used it, it's simply incredible. Within minutes you can get a functioning oAuth2 server up and running and people can log in across the web using your app. However, for our purposes, multiple devices can access the same data from the same entry point. That's the power of building an API driven application. Your data structure remains the same and the methods remain the same for all of your database CRUD methods. You can then consume your API from multiple platforms such as a mobile app and a web app which we will both be building.

If you've been following the tutorials series, we last installed Laravel Socialite: Installing And Configuring Laravel Socialite - Server Side Up. This allowed users to use oAuth to authenticate with social media accounts. Now we will be focusing on our own oAuth server so we can grant credentials to the users to access their application data. Yea it's a lot of oAuth, just wait until we build the mobile app and we have to extend the log in process.

Step 1: Install Passport.

With Laravel 5.4 the in depth instructions are here: API Authentication (Passport) - Laravel - The PHP Framework For Web Artisans. We will go over the parts we need for our SPA and API driven application. The first step is to run:

We've updated to 5.6. Visit the in depth instructions here: API Authentication (Passport) - Laravel

Install Laravel Passport via Composer

composer require laravel/passport

This will include Laravel Passport in our application.

Step 2: Add Passport to Service Providers

Following the 5.6 instructions, we will then add:

Add Passport Service Provider

Laravel\Passport\PassportServiceProvider::class,

to the providers array in config/app.php. After the last tutorial our config/app.php file should have both Socialite and now Passport:

Updated Service Providers Configuration

  /*
   * Package Service Providers...
   */
        Laravel\Tinker\TinkerServiceProvider::class,
        Laravel\Socialite\SocialiteServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class,

Step 3: Migrate the Database

We use the default migrations provided by Laravel Passport. It keeps things simple as Passport comes pre-configured with what is needed for our own oAuth server. Simply run:

Run Database Migrations

php artisan migrate

Your oAuth tokens tables should now be all built! Passport is awesome! For a load more information on oAuth check out: OAuth.com - OAuth 2.0 Servers. It can get complicated, but that site goes through everything!

Step 4: Install Passport with Artisan command

Laravel Passport comes with a slick command to install everything! All you have to do now is run:

Install Passport Keys

php artisan passport:install

You will now have all of the keys created for your grants and tokens for use in your internal application. Only a few more steps and your oAuth Server is configured!

Step 5: Add HasApiTokens trait to your user model

Once again this is in the documentation which is beautifully explained in the Laravel docs in the installation section for Passport API Authentication (Passport) - Laravel - The PHP Framework For Web Artisans. Simply we are telling our User Model that it has the HasApiTokens trait which means that the user can create their own API tokens. This is huge for our SPA since we will be generating a single use API token for our calls in our middleware.

To add the HasApiTokens trait, make sure you include it on top of your User Model. If you've been following along so far, our user model is in /app/User.php. Later on we will move this for easier scalability.

Import HasApiTokens Trait

use Laravel\Passport\HasApiTokens;

We will also have to direct our user to use the HasApiTokens in the model itself:

Add HasApiTokens to User Model

use HasApiTokens, Notifiable;

Our User Model will look like this out of the box:

Complete User Model Implementation

<?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;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Step 6: Register Passport Routes in the AuthServiceProvider.php

Next, we just need to register the Passport routes in our Auth Service Provider. This will register the routes so the user can issue/revoke access tokens.

Open up App\Providers\AuthServiceProvider.php and add use Laravel\Passport\Passport; to the top of the file and Passport::routes(); in the boot() method. Your file should look like this:

AuthServiceProvider Configuration

<?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();
    }
}

Step 7: Set up Passport to be used for incoming API Requests.

We need to set the driver for API authentication to be Laravel Passport. This will come in handy for when we access the API for a user who is logged in through a session with Laravel. It will also check for the access token in the header of a mobile request.

We need to open config/auth.php and swap out:

Original API Authentication Configuration

'api' => [
        'driver' => 'token',
        'provider' => 'users',
],

to

Updated API Authentication Configuration

'api' => [
       'driver' => 'passport',
       'provider' => 'users',
],

Now we are using the passport driver for all of Laravel's API authentication requests.

Step 8: Set Up Your API to be Consumable From The Web

When I was building my first API driven application, this took awhile to find. It's clear in the documentation, just down at the end: API Authentication (Passport) - Laravel - The PHP Framework For Web Artisans What we need to do is add the following line to our Http\Kernel.php file:

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

We will add this to our web middleware array so it will end up looking like this:

Web Middleware Configuration

  /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

What this does, is create a new access token for authenticated users. When an authenticated user makes a request, it will attach the JWT token to the request and allow the user to consume your API. We will go through the VueJS set up in the next tutorial.

Step 9: Clean Up routes/api.php file

This file will house all of your API routes. This is one of the newer features in Laravel where all API routes are registered in this file. It's so awesome for clean development, because it helps groups routes and helps your application scale. I usually clean this up to prepare for the onset of our routes.

By default the routes/api.php file looks like:

Default API Routes File

<?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();
});

What we will do is just simply remove the comment, and then add a route group which will help in the future:

Updated API Routes with Versioning

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
  Route::get('/user', function( Request $request ){
    return $request->user();
  });
});

What we did is simply add a prefix which helps us version our API for future use and growth and add the middleware of auth:api. This automatically applies the API authentication middleware to all of the routes in the function. This way you don't have to explicitly apply the middleware to each individual route. As the app grows, I'll be adding controllers to handle routes, but this is just a simple clean up right away to get us headed in the right spot.

Conclusion

This tutorial simply is a cut down version of the documentation provided here: API Authentication (Passport) - Laravel - The PHP Framework For Web Artisans More configuration options and settings are available in the docs, but we installed what we needed for our uses. In the next tutorial we will start getting into the VueJS functionality and really beginning to shell out our SPA. Of course you can continue checking out all of the code progress here: Roast And Brew - Github.

Want to work together?

Professional developers choose Server Side Up to ship quality applications without surrendering control. Explore our tools and resources or work directly with us.

Join our community

We're a community of 3,000+ members help each other level up our development skills.

Platinum Sponsors

Active Discord Members

We help each other through the challenges and share our knowledge when we learn something cool.

Stars on GitHub

Our community is active and growing.

Newsletter Subscribers

We send periodic updates what we're learning and what new tools are available. No spam. No BS.

Sign up for our newsletter

Be the first to know about our latest releases and product updates.

    Privacy first. No spam. No sharing. Just updates.