Hello Developers,
This tutorial will demonstrate how to set up Laravel Passport in a new Laravel application. Laravel Passport provides a full OAuth2 server implementation for your Laravel application. If your application needs to support OAuth2, then you should use Laravel Passport. Let's jump into the main section.
Install Laravel Project In Your Environment
First, you need to go to your development workspace. My workspace is situated in D:/ drive. Open a command prompt and write the below code to install Laravel.
laravel new laravel_passport_project
Database Configuration
After installing the project, open the project in your code editor. Now we have to configure the database credentials. As I am using the wamp server, I have to start the server and open the localhost/phpmyadmin. In there I will create a database named laravel_passport_project
After that, add the credentials to the project .env file
[project_directory]/.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_passport_project
DB_USERNAME=[USERNAME]
DB_PASSWORD=[PASSWORD]
Install Laravel Passport
As far, we have set up the laravel project and database setup. We want to install a package called Laravel Passport. Laravel Passport builds on top of OAuth2. OAuth means Open Authorization. It is a standard authorization framework for token-based authorization on the internet. OAuth 1 was first published in 2007. Later the protocol was updated to OAuth2 in 2010.
For installing the Laravel Passport, first run the composer command via the Composer package manager
composer require laravel/passport
Laravel Passport comes with its own database migration directory. Thats why we needs to run migrate. In the command prompt run the below command:
php artisan migrate
Sometimes you might get the below error:
If you get the error, simply add the following line in the [project_directory]/app/Providers/AppServiceProvider.php
[project_directory]/app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Schema;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
After that run the php artisan migrate. After that, we need to execute passport:install
Artisan command. This command will create encryption keys needed to generate secure access tokens. In order to run Laravel Passport, simply run the below command:
php artisan passport:install
This will generate some client information for us like the above image.
Configure Laravel Passport
Now configure our model. In User.php model file add hasApiTokens. The complete model is given below:
[project_directory]/app/Models/User.php
<?php
namespace App\Models;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now go to the AuthServiceProvider, we need to be able to revoke the access tokens, clients, and personal access tokens. So we need to use Laravel passport model that has been pulled in. In order to revoke the items we need, we need to call the laravel passport routes inside the boot method. The last thing we need to setup for a Laravel Passport is a driver for api authentication.
[project_directory]/app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
After that, go to the config folder and open auth.php
file. We will find guards, there we need to add some configuration. In api, change the driver = 'token' to passport, Need to change like below:
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false
],
The full code of the auth.php
code is given below:
[project_directory]/config/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
This is the setup for the API authentication. Before we do anything, we need to have a user in our database. This can be done manually through the CLI. But I want to use artisan : tinker in my tutorial. Let’s use that. Execute the below command:
php artisan tinker
Let’s insert data through the below command:
DB::table('users')->insert(['name'=>'Zamil','email'=>'zamil.cse.ruet@gmail.com','password'=>Hash::make('12345678')]);
This code will create a user named Zamil, email zamil.cse.ruet@gmail.com, hashed password. As you get true, that means the user created in the user's table in the database.
We have completely set up the laravel project with laravel passport as API authentication. Hope this might help you in the journey of development.
Read More: Learn about Artisan CLI in Laravel