Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.
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.
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.
composer require laravel/passport -w
php artisan migrate
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:
php artisan passport:install
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 that 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;
}
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',
],
],
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
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 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');
}
We'll create simple user authentication methods via Laravel passport below.
routes/api.php
that point to AuthController
:<?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::group([
'prefix' => 'auth'
], function () {
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']);
});
});
php artisan make:controller AuthController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Models\User;
use Validator;
class AuthController extends Controller
{
/**
* Create user
*
* @param [string] name
* @param [string] email
* @param [string] password
* @param [string] password_confirmation
* @return [string] message
*/
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|',
'c_password'=>'required|same:password',
]);
$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'=>'Provide proper details']);
}
}
}
TEST register user API using postman
AuthController.php
, create a simple login method that generates API token
via passport:/**
* Login user and create token
*
* @param [string] email
* @param [string] password
* @param [boolean] remember_me
* @return [string] access_token
* @return [string] token_type
* @return [string] expires_at
*/
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
/**
* Get the authenticated User
*
* @return [json] user object
*/
public function user(Request $request)
{
$user = Auth::user();
return response()->json($user);
}
TEST get user API using postman
AuthController.php
, create a simple method to revoke
the token from the user:/**
* Logout user (Revoke the token)
*
* @return [string] message
*/
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
TEST logout user API using postman