In this tutorial you will learn about the Laravel 7/6 REST API With Passport Auth Tutorial and its application with practical example.
In this Laravel 7/6 REST API With Passport Auth Tutorial, i will show you how to create rest api in laravel 7/6 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 7/6 REST API With Passport Auth Tutorial
- Step 1: Install Fresh Laravel Setup
- Step 2: Configure Database Details
- Step 3: Install Passport Package In Laravel
- Step 4: Run Migration and Install Passport Auth
- Step 5: Laravel Passport Configuration
- Step 6: Create APIs Route
- Step 7: Create Controller & Methods
- Run Development Server
- Test Laravel 8 REST CRUD API with Passport Auth in Postman
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.
Laravel 7/6 REST API With Passport Auth Tutorial
In this step by step tutorial I will demonstrate you how to create REST API With Passport authentication in laravel.
- Step 1: Install Fresh Laravel Setup
- Step2: Configure Database Details
- Step 3: Install Passport Packages in Laravel
- Step 4: Run Migration and Install Passport Auth
- Step 5: Passport Configuration
- Step 6: Create APIs Route
- Step 7: Create Controller & Methods
- Step 8: Now Test Laravel REST API in Postman
Step 1: Install Fresh Laravel Setup
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Configure Database Details
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=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Step 3: Install Passport Package In Laravel
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 successfully install laravel passport, register providers. Open config/app.php . and put the bellow code :
1 2 3 4 5 |
// config/app.php 'providers' =>[ Laravel\Passport\PassportServiceProvider::class, ], |
Before you run migration command, go to the app/providers/AppServiceProvider.php and put the two line of code inside a boot method :
1 2 3 4 |
Use Schema; public function boot() { Schema::defaultStringLength(191); } |
Step 4: Run Migration and Install Passport Auth
In this step we will migrate default database schema, run following command to migrate database schema.
1 |
php artisan migrate |
Now, you need to install laravel to generate passport encryption keys. This command will create the encryption keys needed to generate secure access tokens. like secret key and secret id.
1 |
php artisan passport:install |
Step 5: Laravel Passport Configuration
Now, go to App folder and open User.php file. Then put the following code into User.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?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', ]; } |
now, we will Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and update this line => Register Passport::routes(); inside of boot method
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(); } } |
config/auth.php
Now, go to config/auth.php and open auth.php file. Now, Change API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API
1 2 3 4 5 6 7 8 9 10 |
[ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], |
Step 6: Create APIs Route
Now, go to routes folder and open api.php. Then update the following routes into api.php file:
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'); }); }); |
Step 7: Create Controller & Methods
Now, lets create a controller named AuthController using command given below –
1 |
php artisan make:controller Api\AuthController |
Now, we need to create some methods in AuthController.php. So navigate to app/http/controllers/Api folder and open AuthController.php file. Then update the following methods into your AuthController.php file:
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 44 |
<?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); } } |
Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Test Laravel 8 REST CRUD API with Passport Auth in Postman
Now, we will call above create crud and auth apis in postman app:
1 – Laravel Register Rest API :
2 – Login API :
Next Step, you will call getUser, create product, list product, edit product, and delete product APIs, In this apis need to pass the access token as headers:
1 2 3 4 |
‘headers’ => [ ‘Accept’ => ‘application/json’, ‘Authorization’ => ‘Bearer ‘.$accessToken, ] |