A modern REST API in Laravel 5 Part 4: Authentication using Laravel Passport

Introduction
OAuth is all around us. Most of us have tried to login to a 3rd party service using our Facebook or Google account as a login. This login mechanism is one of many OAuth authentication types. However, you can also use OAuth to generate simple API keys. One of the OAuth authentication types generates API keys based on username and password and is therefore a solid authentication choice for SaaS-style apps. This article will explore how to setup the password grant authentication type in Laravel using Laravel Customize Password Token .

Agenda
During this article we will explore topics such as…

Learn how authenticating an API with OAuth 2 works
How we can implement user-based authentication using Laravel Passport
How we can scope API requests to the current user
OAuth 2 authentication for dummies
There are a lot of good in-depth resources on OAuth and it’s many use cases. For instance the official spec. If you have the time and the motivation go read it. A little bit too technical/time consuming for you? You have come to the right place.

The 2-minute introduction to OAuth grants
OAuth let’s you authenticate using different methods – these methods are called grants. This article will not focus on all of them. Here is a quick run-down of the grants.

Grant type Used for
Client Credentials When two machines need to talk to each other, e.g. two APIs
Authorization Code This is the flow that occurs when you login to a service using Facebook, Google, GitHub etc.
Implicit Grant Similar to Authorization Code, but user-based. Has two distinct differences. Outside the scope of this article.
Password Grant When users login using username+password. The focus of this article.
Refresh Grant Used to generate a new token when the old one expires. Also the focus of this article.
I realize this is a simplification of the grants. If you want a more in-depth description I highly recommend either the official spec or the descriptions on The PHP League’s OAuth 2 package website.

If you came here for a description on how to implement Client Credential, Authorization Code or Implicit Grants I hate to disappoint you. The focus point of this article is password grants and refresh grants. That being said you might learn a trick or two, so please do stick around 🙂

How password+refresh authentication works
This article will describe how to create a typical SPA (single page application) style login flow using the password and refresh grants. This might seem daunting at first but it is actually pretty simple once get to know the concepts.

7………….

Make an OAuth2 server using Laravel Passport

If you have ever had to create an OAuth server you would agree with me that it can be difficult and time-consuming. Luckily, there is a Laravel package that makes this job easier: Laravel Passport. In this article, we will consider how you can use this amazing package to create your own OAuth server.

For this article, we will be leveraging on an existing Laravel application. A todo application built using Laravel. We will assume, for the sake of this article, that you have created the application and it already works, but you want to add an OAuth server so other applications can connect to the service securely.

The source code to the todo application is available on GitHub.

⚠️ This is not an OAuth or Laravel tutorial, so this article will focus solely on how you can use Laravel Passport to create an OAuth server on an existing application. If you want to learn more about Laravel or OAuth, you can look here and here respectively.

Setting up our application without an OAuth server
Before we start setting up, make sure you have the following requirements ready as they will be necessary to follow through this article:

NPM installed on your local machine.
PHP 7 or later installed locally.
Composer installed on your local machine.
Knowledge of Laravel PHP framework.
Knowledge of OAuth and how it works.
Now that the requirements are defined, let’s move on. The first thing you need to do is download or clone the entire repository to the application we want to create.

Anatomy of the downloaded repository
Let us quickly look at what we have downloaded. There are three directories; all of them are Laravel applications. In the directory we have:

The to-do app without OAuth server installed (our starting point).
The completed to-do app with the OAuth server installed (for reference).
The consumer app (for reference).
Copy the todo application without OAuth installed as that is what we will be working with.

Setting up our starting point to-do application
To set up the todo application, copy the directory todoapp – no oauth server to a different directory and rename it to whatever you wish to rename it to.

For the sake of brevity, we will be using SQLite to create a quick connection to a database. Create a new and empty file: ./database/database.sqlite.

Next, copy the .env.example file from the root of your project to .env and in the new file, change the DB_CONNECTION key to sqlite. Now delete every other DB_* key in the .env file leaving only the DB_CONNECTION key. If you cannot find the .env.example file, it is because it may be hidden in your file system. Open the project in Sublime Text or your preferred code editor and you’ll see the file.

To get started, cd to your project folder in your terminal and run the commands below to install the composer packages, run the migration on the database, and generate an application key respectively:

# @see https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx on how to install Composer globally
$ composer install

# Run migrations on the database
$ php artisan migrate

# Generate a secure application key
$ php artisan key:generate

After the commands have finished running, run the command below to start a PHP server using artisan.

$ php artisan serve

💡 The artisan serve command quickly brings up a PHP server and helps you quickly run your Laravel application without having to worry about setting up Virtual Hosts.

Now, when you visit http://127.0.0.1:8000 you should see the Laravel homepage. Click on the register and create a new account, we will need this later.

Once you’re in the application, click the “Add” button to add a bunch of to-dos to your application. You can also tick a few as completed while you are at it. When you are done you should have something similar to this:

Adding an OAuth2 Server to our Laravel Application
Now that the application is running correctly, you should return to your command-line and terminate the server by using cmd+c (ctrl+c on windows).

Installing and configuring Laravel Passport
The first thing we would do is install Laravel Passport. We can do so by running the following command on our terminal:

$ composer require laravel/passport

This will install the Laravel Passport composer package to our Laravel application, now if you are using Laravel 5.5 or higher, (our current application is) then that is all you need to do to configure Laravel Passport. However, if you are using Laravel 5.4 or lower, you will need to register the Passport service provider in the providers array of your config/app.php configuration file:

Laravel\Passport\PassportServiceProvider::class,

Now, you need to run the migration that will create all the required database tables that Laravel Passport will need. To do this run:

$ php artisan migrate

Next, you will need to run the command that will generate an encryption key. This encryption key will let passport securely generate access tokens. The command will also create a personal access client and a password client for us.

$ php artisan passport:install

Next, add the Laravel\Passport\HasApiTokens trait to your App\User model. This trait will provide some helper methods which allow you to inspect the authenticated user’s token and scopes:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable {
    use HasApiTokens, Notifiable;
}

Open the AuthServiceProvider and inside the register method of the class make a call to Passport::routes as shown below (Note that you need to add the use line to import the Laravel Passport package):

use Laravel\Passport\Passport;
// ...

class AuthServiceProvider extends ServiceProvider
{
    // ...

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

Now, to the last part of configuring Laravel Passport. Open the ./config/auth.php file. Set the driver option of the api authentication guard to “passport”. This will make sure your application uses Passport’s TokenGuard while authenticating incoming API requests:

'guards' => [
    //...

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

With that we have finished configuring Laravel Passport and we are ready to start using it in our application.

Adding a User Interface for managing OAuth clients and tokens
Since we have finished installing Laravel Passport, we want to leverage on some of the things Laravel Passport offers us out of the box. One of them is a User Interface where users can manage client applications, revoke access tokens etc.

Run the command below:

$ php artisan vendor:publish --tag=passport-components

This will publish some Vue components for plug-and-play usage. If you look at the ./resources/assets/js/components directory, you should see a passport directory with three Vue components inside. Let’s load them up into the application so we can use them.

Open the ./resources/assets/js/app.js file and in there paste in the following right under the todos component (Note that it MUST be added before the const app = new Vue instance is created):

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

In the above, we are registering the Vue components that were published using the artisan vendor publish command above. This will make the components available throughout our application if we wanted to use them. Great!

Now run the command below to install the Node packages and rebuild our assets using webpack:

$ npm install
$ npm run dev

After the build is completed, we will need to create a settings page where the passport views will reside.

Create a new controller using the command below

$ php artisan make:controller SettingsController

Open the newly created controller and replace with the code below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('settings');
    }
}

In the controller above we setup a middleware that only allows logged-in users to access the index method. Next, we render a view settings.

Create a new view settings.blade.php in the ./resources/views directory and in there add the code below:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">            
            <passport-authorized-clients></passport-authorized-clients>
            <passport-clients></passport-clients>
            <passport-personal-access-tokens></passport-personal-access-tokens>
        </div>
    </div>
</div>
@endsection

In the code above we have added the Vue components we imported earlier into our view. This will generate an entire OAuth management tool for the user no further work needed on that front.

Next, we will create a route to expose the controller and view we just created. To do this, open the ./routes/web.php file and add the route below:

Route::get('/settings', 'SettingsController@index')->name('settings');

Finally, we want to add a Settings link to the page so it is easily accessible. Open the ./resources/views/layouts/app.blade.php and on line 55 (or anywhere in the Bootstrap navigation menu you want) add the code below:

<li><a href="{{ route('settings') }}">Settings</a></li> 

This will just create a link to the settings page. Now run php artisan serve again like you did before and visit the link http://127.0.0.1:8000, then log in and click Your Name > Settings; you should see a page like this below:

Creating an OAuth application
Now you should go ahead and create an OAuth client, we will be needing it in the next section. Click the “Create new client” link and create a new OAuth application. For the tutorial, set the Redirect URL to http://127.0.0.1:8001/callback.

⚠️ When creating your own OAuth application consumer, the redirect URL will be the address to the actual callback on the consumer.

Once you have created it you should see your client with an ID and Secret. We will use this information to test our consumer application.

Exposing an endpoint to test the Laravel Passport OAuth Server implementation
The last thing we will do with our OAuth server enabled application is, create an endpoint that will respond to request using Laravel Passport.

Open the ./routes/api.php file and add the following route:

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

The route above sets a middleware auth:api which instructs the route to only allow applications authenticated with Laravel Passport to access this route. Then once it’s validated, it returns all the user’s todos.

Comments are Disabled