In this tutorial you will learn about the Create REST API With Passport Authentication In Laravel 5.8 and its application with practical example.
Laravel 5.8 Create REST API With Passport Authentication
In this tutorial, i will show you how to create rest api in laravel 5.8 application with passport authentication. In this tutorial we will be using passport for api authentication. we will create register and login api with simple retrieve user details.
Laravel comes with default login authentication, but when we want to create APIs we have to use tokens instead of sessions for authenticating users, as APIs does not support session variables. After login via API, user must be assigned a token and sent back to the user which is further used for authenticating API requests. Laravel provides Passport authentication which makes it easy creating REST APIs in laravel.
Install Laravel 5.8
First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larablog DB_USERNAME=root DB_PASSWORD= |
Install Passport Package
In this step, we need to install Laravel Passport package via the composer dependency manager. Use the following command to install passport package.
1 |
composer require laravel/passport |
After Installing ‘laravel/passport’ package, we need to add service provider in config/app.php file as following.
config/app.php
1 2 3 4 |
'providers' => [ .... Laravel\Passport\PassportServiceProvider::class, ] |
Run Migration and Install Laravel Passport
After successfully installing ‘laravel/passport’ package, we require to create default passport tables in our database. so let’s run the following command to migrate Laravel Passport tables to your database.
1 |
php artisan migrate |
Now, it is mandatory to install passport using the command below. This command will generate encryption keys required to generate secret access tokens.
1 |
php artisan passport:install |
Laravel Passport Configuration
Now, we need to make following changes in our model, service provider and auth config file to complete passport configuration. Open App/User.php model file and add ‘Laravel\Passport\HasApiTokens’ trait in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Laravel\Passport\HasApiTokens; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements MustVerifyEmail { 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', ]; } |
Next Register passport routes in App/Providers/AuthServiceProvider.php, open App/Providers/AuthServiceProvider.php and put “Passport::routes()” inside the boot method like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?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(); } } |
Now open config/auth.php file and set api driver to passport instead of session.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php return [ ..... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], ..... ] |
Create API Routes
Let’s create API routes. Open routes/api.php file create api routes as below –
1 2 3 4 5 6 7 |
Route::prefix('v1')->group(function(){ Route::post('login', 'Api\AuthController@login'); Route::post('register', 'Api\AuthController@register'); Route::group(['middleware' => 'auth:api'], function(){ Route::post('getUser', 'Api\AuthController@getUser'); }); }); |
Create Authentication Controller
Now, create a Authentication Controller name AuthController. Use the below command to create controller.
1 |
php artisan make:controller Api\AuthController |
Once the above command executed, it will create a resource controller file “AuthController.php” in “app/Http/Controllers/Api” directory. Go to “AuthController.php” and put the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; use Validator; class AuthController extends Controller { public $successStatus = 200; public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $success['token'] = $user->createToken('AppName')->accessToken; return response()->json(['success'=>$success], $this->successStatus); } public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $success['token'] = $user->createToken('AppName')-> accessToken; return response()->json(['success' => $success], $this-> successStatus); } else{ return response()->json(['error'=>'Unauthorised'], 401); } } public function getUser() { $user = Auth::user(); return response()->json(['success' => $user], $this->successStatus); } } |
Start Application Server
Lets start the development server using following artisan command –
1 |
php artisan serve |
Testing the REST API
Our Authentication API is ready to test. I will use Postman to test the API.
Register Api :-
Verb: POST
URL :http://localhost:8000/Api/v1/register
Login Api :-
Verb: GET
URL :http://localhost:8000/Api/v1/login
getUser Api :-
Verb: GET
URL: http://localhost:8000/Api/v1/getUser
When testing getUser API it requires user to be authenticated, you need to specify headers. Make sure in getUser api we will use following headers as listed bellow.
1 2 3 4 |
'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer '.$accessToken, ] |
Basically, you have to specify access token as a Bearer token in the Authorization header. The access token is what you received after login and registration.