Laravel Passport
Laravel API authentication using passport
Introduction
Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.
Passport Or Sanctum?
Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel sanctum . If your application absolutely needs to support OAuth2, then you should use Laravel Passport.
However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.
api()
features.
Installation
To get started, install Passport via the Composer package manager:
composer require laravel/passport
Passport's service provider registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:
php artisan migrate
Next, you should execute the passport:install
Artisan command. 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:
Client
model instead of auto-incrementing integers, please install Passport using the
uuids option.
After running the passport:install
command, add the Laravel\Passport\HasApiTokens
> trait to your App\Models\User
model. This trait will provide a few helper methods to your
model which allow you to inspect the authenticated user's token and scopes. If your model is already using the Laravel\Sanctum\HasApiTokens
trait, you may remove that trait:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Next, you should call the Passport::routes
method within the boot
method of your App\Providers\AuthServiceProvider
. This method will register the routes necessary to issue
access tokens and revoke access tokens, clients, and personal access tokens:
<?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\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
if (! $this->app->routesAreCached()) {
Passport::routes();
}
}
}
Finally, in your application's 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:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Client UUIDs
You may also run the passport:install command with the --uuids option present. This option will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport Client model's primary key values. After running the passport:install command with the --uuids option, you will be given additional instructions regarding disabling Passport's default migrations:
php artisan passport:install --uuids
Deploying Passport
When deploying Passport to your application's servers for the first time, you will likely need to run the passport:keys
command. This command generates the encryption keys Passport needs in order to
generate access tokens. The generated keys are not typically kept in source control:
php artisan passport:keys
If necessary, you may define the path where Passport's keys should be loaded from. You may use the Passport::loadKeysFrom
method to accomplish this. Typically, this method should be called from the
boot
method of your application's
App\Providers\AuthServiceProvider
class:
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::loadKeysFrom(__DIR__.'/../secrets/oauth');
}
Passport Authentication
Below are some authentications sample code to authenticate users via Laravel Passport.
Step 1:Create Route
Open api.php
from routes folder, and replace the code of route with the following:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', [AuthController::class, 'login']);
Route::post('register', [AuthController::class, 'register']);
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout', [AuthController::class, 'logout']);
Route::get('user', [AuthController::class, 'user']);
});
Step 2:Create Controller
php artisan make:controller AuthController
Step 3:Register User API
Open Http/Controllers/AuthController.php
and replace the code with below code:
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users,email',
'password' => ['required', Password::min(8)->mixedCase()->letters()->numbers()->symbols()->uncompromised(),],
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
if ($user->save()) {
return response()->json([
'message' => 'Successfully created user!'
], 201);
} else {
return response()->json(['error' => 'Something went wrong, check details']);
}
}
TEST register user API using postman
We can also try to access the same route with an empty email column. We should receive an required error.
Step 4: Login User API
In the same file
Http/Controllers/AuthController.php>
, add below code after register method:
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' => 'Unauthorized'
], 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([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
TEST Login user API using postman
Step 5: Get User API
In the same file
Http/Controllers/AuthController.php
, add below code after Login method:
/**
* Get the authenticated User
*
* @return [json] user object
*/
public function user(Request $request)
{
return response()->json($request->user());
}
TEST get user API using postman