In this tutorial you will learn about the Laravel 7 Passport Refresh Token Example and its application with practical example.
In Laravel creates rest API with passport refresh token example tutorial, I’ll show you how to create restful api with laravel passport refresh token example.
In this tutorial you will learn step by step how to create rest API with passport refresh token in laravel. You will also learn how to set passport token expired time in this example and also get access token in laravel apps.
Laravel Create REST API with Passport Refresh Token Example Tutorial
In this step by step tutorial you will be able to create laravel api authentication and token with passport refresh token laravel apps:
- Download Laravel New App
- Add Database Detail
- Install Passport Packages in Laravel
- Run Migration and Install Passport Auth
- Configuration Passport Package
- Create APIs Route
- Create Controller & Methods
- Now Test Laravel REST API in Postman
Install Laravel Application
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 |
Database Configuration
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 7 8 9 10 11 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db name DB_USERNAME=db user name DB_PASSWORD=db password |
Install Passport Package In Laravel
In this step, you need switch to project directory and the following commands:
1 2 3 |
composer require laravel/passport composer require guzzlehttp/guzzle composer require symfony/psr-http-message-bridge |
Once you have installed laravel passport, register providers. Open config/app.php. So update the following code into config/app.php file:
config/app.php
1 2 3 |
'providers' =>[ Laravel\Passport\PassportServiceProvider::class, ], |
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); } |
Run Migration and Install Passport Auth
Now, run the following migration command.
1 |
php artisan migrate |
Next, you need to generate a passport encryption key. So run the following command.
1 |
php artisan passport:install |
Configuration Passport Package
Now, we need to configure passport package. Go to App/User.php file and update the following code into your App/User.php file as following:
App/User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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 you need to register passport package in AuthServiceProvider.php So go to App/Providers/ and open AuthServiceProvider.php. Then update the file as following:
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 |
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; use Laravel\Passport\Passport; use Carbon\Carbon; 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(); Passport::tokensExpireIn(Carbon::now()->addDays(1)); Passport::refreshTokensExpireIn(Carbon::now()->addDays(10)); } } |
config/auth.php
Now, go to config/auth.php and Change the API driver to the session to passport. Put this code
1 |
‘driver’ => ‘passport’ |
in API as following:
1 2 3 4 5 6 7 8 9 10 |
[ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], |
Create APIs Route
Now, you need to create rest API routes. Go to routes/api.php put the following routes into api.php file:
routes/api.php
1 2 3 4 |
Route::prefix('v1')->group(function(){ Route::post('login', 'Api\AuthController@login'); Route::post('register', 'Api\AuthController@register'); }); |
Create Controller & Methods
Now, run the following command to create a controller:
1 |
php artisan make:controller Api\AuthController |
After that, update the following methods into AuthController controller as following:
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 45 46 47 48 49 50 51 52 53 54 55 |
<?php namespace App\Http\Controllers; use App\User; use Validator; use Exception; use GuzzleHttp\Client; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Laravel\Passport\Client as OClient; class AuthController extends Controller { public $successStatus = 200; public function login() { if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) { $oClient = OClient::where('password_client', 1)->first(); return $this->getTokenAndRefreshToken($oClient, request('email'), request('password')); } else { return response()->json(['error'=>'Unauthorised'], 401); } } public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $password = $request->password; $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $oClient = OClient::where('password_client', 1)->first(); return $this->getTokenAndRefreshToken($oClient, $user->email, $password); } public function getTokenAndRefreshToken(OClient $oClient, $email, $password) { $oClient = OClient::where('password_client', 1)->first(); $http = new Client; $response = $http->request('POST', 'http://mylemp-nginx/oauth/token', [ 'form_params' => [ 'grant_type' => 'password', 'client_id' => $oClient->id, 'client_secret' => $oClient->secret, 'username' => $email, 'password' => $password, 'scope' => '*', ], ]); $result = json_decode((string) $response->getBody(), true); return response()->json($result, $this->successStatus); } } |
In the above controller, getTokenAndRefreshToken() method will generate passport token and refresh token for your laravel apps. Now, Open your terminal and run the following command to start the development server:
1 |
php artisan serve |
Now Test Laravel REST API in Postman
Now, we are good to teat API in postman