In this article, I will show you how to setup Laravel to work with as REST API (Representational state transfer Application programming interface) we will use the authenticate server method OAuth2 to login to our API. Ok, let’s get started with project requirements.
Requirements
As always we will use composer to install packets.
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, then that is all you need to do to configure Laravel Passport.
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 the 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 class Laravel\Passport\HasApiTokens to your ‘user‘ model located in App\Admin.php. For this project, I’m using a custom authentication model. This class will provide some helper methods which allow you to inspect the authenticated user’s token and scopes your user model should look like:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class Admin extends Authenticatable { use HasApiTokens, Notifiable; protected $guard = 'admin'; protected $fillable = [ 'login', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
Authorization
I’m making a little change here except standard Laravel logic. I’m changing users to admins for our API we will use authenticated class imported from Passport, have a look on /config/auth.php file:
<?php return [ 'defaults' => [ 'guard' => 'admin', 'passwords' => 'admins', ], 'guards' => [ 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'client' => [ 'driver' => 'session', 'provider' => 'clients', ], 'api' => [ 'driver' => 'passport', 'provider' => 'admins', ], ], 'providers' => [ 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ], 'clients' => [ 'driver' => 'eloquent', 'model' => App\Client::class, ], ], 'passwords' => [ 'admins' => [ 'provider' => 'admins', 'table' => 'password_resets', 'expire' => 60, ], 'clients' => [ 'provider' => 'clients', 'table' => 'password_resets', 'expire' => 60, ], ], ];
Controller
We are creating PassportController. In the controller, we can store all functions and methods for our API. In my example, I will create two functions. The first function will check login cardinals and on success will return an authorization token if email and password don’t match as return we will send JSON format with error and 401 code.
public function login() { $inputs = Request::all(); $credentials = [ 'email' => $inputs['email'], 'password' => $inputs['password'] ]; if (auth()->attempt($credentials)) { $token = auth()->user()->createToken('PBXAPIResseller')->accessToken; return response()->json(['token' => $token], 200); } else { return response()->json(['error' => 'UnAuthorised'], 401); } }
The second function will return JSON format the values of the Voipswitch database plans. On failure, we will return JSON failed message with the code 500. Please note it is only an example and you can put any function here. I’m only showing you the logic.
public function get_plan() { $inputs = Request::all(); try { $plan = \DB::connection('mysql2') ->table('plans') ->select('id_plan', 'name', 'description', \DB::raw("ROUND(startup_cost, 2) as startup_cost"), \DB::raw("ROUND(period_cost, 2) as period_cost"), 'period_number') ->where('id_plan', $inputs['id_plan']) ->first(); Log::channel('api')->info('get_plan : id_plan='.$inputs['id_plan']); return response()->json([$plan], 200); } catch(\Illuminate\Database\QueryException $ex){ Log::channel('api')->error('get_plan : id_plan='.$inputs['id_plan']); return response()->json(['Failed', $ex->getMessage()], 500); } }
Route
For the API we need to use routing file ‘/routes/api.php‘. All POST request will be guarded by Authentication controller ‘middleware(‘auth:api’)’, so only logged users can use POST routes other will be rejected.
Please have look on example routing file.
<?php use Illuminate\Http\Request; Route::post('login', 'PassportController@login'); Route::middleware('auth:api')->group(function () { Route::post('get_plan', 'PassportController@get_plan'); });
Testing
For testing, I will use Postman software. We need to sent first POST ‘/login‘ request as a response I should get an authorization token from OAuth2 class. Now I can use this ‘token‘ for any configured requests. Please check the example. POST URL: http://localhost/api/login with params: email: admin@hello.com and password.
on return, we got the ‘token‘ now we need to use this token for Authorization Header. We need to add two things on request header before we sent the request to API.
Accept: application/json Authorization: Bearer $token
In our example, we can now send the POST call ‘get_plan‘ URL: http://localhost/api/get_plan with input param id_plan
on return, we have plan info from the database.
That’s it now we have our Laravel REST API for any purpose with authentication OAUTH2 using a token. That means that only registered users can use our API. I hope you like this material. Please leave a comment for any queries or doubts.