Authenticating Laravel APIs Using Passport
Knowledge of authentication and security procedures are important in the day to day process of building and managing applications today. In this tutorial, we will learn how to add authentication to a Laravel API using Passport.
APIs are known to authenticate users using tokens as they do not maintain session between requests. With the Laravel framework, authenticating APIs has been really simplified using Laravel passport, a package helps to implement a full OAuth2 server for your Laravel powered application.
Create a Laravel project scaffolding by running either of the following commands
composer create-project --prefer-dist laravel/laravel laravel_passport_api
#or
laravel new laravel_passport_api
Once the project scaffolding has been generated, navigate to the laravel_passport_api folder and install passport by running
composer require laravel/passport
Next, open up your .env file and add your database credentials then run the migrations to create the necessary database tables laravel and passport provides using:
php artisan migrate
After running the preceding command, you should get a response (from the terminal) similar to:
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (6.69 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (2.07 seconds)
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrated: 2016_06_01_000001_create_oauth_auth_codes_table (3.06 seconds)
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrated: 2016_06_01_000002_create_oauth_access_tokens_table (3.66 seconds)
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrated: 2016_06_01_000003_create_oauth_refresh_tokens_table (2.88 seconds)
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated: 2016_06_01_000004_create_oauth_clients_table (1.51 seconds)
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table
Migrated: 2016_06_01_000005_create_oauth_personal_access_clients_table (0.38 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.55 seconds)
Configuring Passport
Open up your terminal and run the command below to create the tokens for security:
php artisan passport:install
To implement passport authentication in our API, we need to use the HasApiTokens
trait that passport provides for us in the user model of our application.
To achieve this, edit App/User.php
as such.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Next, call Passport::routes()
in the boot()
method of your app/Providers/AuthServiceProvider.php
file as such:
<?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
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
Once that is set up, the next step is to set passport as the default method for authenticating our API. In order to do this modify the 'guards'
array in our config/auth.php as such:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Building a Simple API Authentication System using Passport
Now that we have passport installed and configured in our application, we need to create the controllers for users to register and log in to our application using tokens.
Open up routes/api.php
and add the following lines to register the authentication routes
Route::post('login', 'UserController@login');
Route::post('register', 'UserController@signup');
Create the corresponding controller by running:
php artisan make:controller UserController
The command above creates a file named UserController.php in the App/Http/Controllers
folder. Open it up and include the necessary methods for signup and login as thus:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
class UserController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'confirm_password' => 'required|same:password',
]);
$data = $request->all();
$data['password'] = bcrypt($data['password']);
User::create($data);
return response()->json(['message'=> 'user created successfully'],201);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Authorization failed'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'message' => 'Authorization Granted',
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
}
Sending Requests to the API:
Serve the application by running:
php artisan serve
You can now proceed to send requests using postman or any API client of your choice and you’d get responses similar to those below.
You can check out the source code of the full application on GitHub here: