In first step, we require to get fresh Laravel application using bellow command, So open your terminal or command prompt and run bellow command:
laravel new auth
Step 2. Install Laravel Passport Package
Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.
composer require laravel/passport
Step 3. Run Migration
The Passport migrations will create the tables your application needs to store clients and access tokens.
php artisan migrate
Step 4. Generate keys
This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:
php artisan passport:install
After running this command, add the Laravel\Passport\HasApiTokens trait to your App\Usermodel. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:
Step 5. Passport Config
<?phpnamespace App;use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;class User extends Authenticatable
{
use Notifiable, HasApiTokens;
}
Next, you should call the Passport::routes method within the boot method of your AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
<?phpnamespace 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();
}
}
Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests: