Laravel support many types of authentications like session, files, tokens with the website, but what about the APIs outside the site or a web service calls from mobile application. Till now we were using the “once:basic” method to authorise the external request from mobile application request of API request.
From Laravel 5.3, it came up with the amazing authentication method called “Passport” to authorise the external request from the internet like accessing the data using API calls as well as the web service calls from the android or IOS mobile applications.
Laravel Passport provides OAuth2 server implementation in a couple of minutes.
I found many developers have only one question which is “Laravel Passport is a very good method to authorise the third party requests, but how do I implement Laravel Passport with the mobile application web-calls/web APIs/web services calls“.
So to get rid out of this, let’s dive into the implementation of Laravel Passport Authentication.
To get started we have to install Laravel Passport into our application, we will do the same via composer.
Open the command prompt in windows and terminal in mac. I assume that your present working directory is the application in which you are going to implement the Passport authentication. Fire below command to install Passport.
composer require laravel/passport
Next, to use the Passport in our application we have to register it as a provider in the array of “providers” in “config/app.php” file. add below line in an array called “providers“.
Laravel\Passport\PassportServiceProvider::class,
Passport will use it’s own database tables to configure and authorise the requests. So once you get it done with the above things let’s migrate the database with the Passport migrations. Fire below command in your terminal.
php artisan migrate
This will create the tables which are required to store the access tokens of the authorized users. Now let’s fire last command of the passport installation process.
php artisan passport:install
This command will install Laravel Passport service in your application, and will create the encryption keys to generate the secure access tokens for the authorised users.
After firing the above command let’s add the “HasApiTokens” trait to the “app\User” model. By this you can inspect the user’s token and scopes. add below line over the class definition.
use Laravel\Passport\HasApiTokens;
Add below code inside the class definition.
use HasApiTokens, Notifiable;
The whole “App\User” model will look like:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use Notifiable, HasApiTokens; }
Now let’s edit the “AuthserviceProvider”. Open “app\Providers\AuthServiceProvider.php” and add below line above the class definition.
use Laravel\Passport\Passport;
Add below line in the boot() method of the AuthServiceProvider class
Passport::routes();
This will register the routes which are required to use Passport authentication.
Finally let’s update the authentication guard in “config/auth.php” let’s update the driver of the api authentication guard to passport instead of tokens.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'tokens', 'provider' => 'users', ], ],
Replace above guards array with the below one in auth.php file
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
Whohaaa! all the configurations have been completed now let’s add api routes and start using the APIs via passport authorisation. As we are registering routes for the APIs, we will add the routes in “api.php” file.
Open routes\api.php file and add below route to access the login api.
Route::group(['namespace' => 'api'], function () { Route::get('/login', 'UserController@login'); });
Above route will point the login() method of the UserController class. Let’s create UserController in app\Http\Controllers\api by artisan command:
php artisan make:controller api\UserController
Now open UserController class file and add the login() method code which will authorise the user and send the accessToken in the response after successful authorisation.
The UserController file will look like below.
<?php namespace App\Http\Controllers\api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\User; use Response; class UserController extends Controller { public function __construct(){ $this->content = array(); } public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $this->content['token'] = $user->createToken('Pizza App')->accessToken; $status = 200; } else{ $this->content['error'] = "Unauthorised"; $status = 401; } return response()->json($this->content, $status); } }
The above code will authorise the valid user and redirect the user to login page if not valid. But as we are using this API from mobile application we are supposed to send the response, instead of redirecting the user login. To do this we have to send “Accept : application/json” along with the header. This will send the response in json format and will not redirect the user to login page.
As we assume that user has been authorised successfully and received the accessToken, now we will use that access token while requesting other APIs. You have to send the accessToken in Authorization header along with the Bearer keyword, refer below screenshot.
While this request the below code has been run to return the response of the user details. Now the UserController will look like below:
<?php namespace App\Http\Controllers\api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\User; use Response; class UserController extends Controller { public function __construct(){ $this->content = array(); } public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $this->content['token'] = $user->createToken('Pizza App')->accessToken; $status = 200; } else{ $this->content['error'] = "Unauthorised"; $status = 401; } return response()->json($this->content, $status); } public function details(){ return response()->json(['user' => Auth::user()]); } }
That’s it. you can add other controllers and methods like above.
Cheers!!! :)