Hi Brothers ,
Laravel Passport is a robust and secure package for API authentication using OAuth2 in Laravel applications. It allows you to authenticate API requests using access tokens, which makes it ideal for building APIs that require user authentication, such as mobile apps, SPAs, or third-party integrations. This guide will walk you through the installation and setup process of Laravel Passport from start to finish.
Prerequisites
Before you begin, ensure that you meet the following requirements:
Let's see the below steps and make it done.
If you haven't already, create a new Laravel application by running
composer create-project --prefer-dist laravel/laravel laravel-passport-app
This will set up a new Laravel project in the laravel-passport-app directory.
Laravel Passport can be installed via Composer. Open your terminal and run the following command inside your Laravel project directory
composer require laravel/passport
This will install the Passport package and all its dependencies..
After installing the package, you need to publish Passport's configuration and migration files. Run the following command to publish the necessary files
php artisan vendor:publish --provider="Laravel\Passport\PassportServiceProvider"
This will publish the Passport configuration file (config/passport.php) and the migration files required for OAuth2 support.
Laravel Passport comes with migrations that define the necessary tables to store clients, access tokens, and refresh tokens. Run the following Artisan command to migrate the tables
php artisan migrate
This will create the necessary tables in your database. Ensure your .env file is properly configured to connect to your database before running the migration.
Passport uses encryption keys to generate secure access tokens. To generate these keys, run the following command
php artisan passport:install
This will generate encryption keys and store them in the storage/oauth-private.key and storage/oauth-public.key files. These keys are used for issuing and validating access tokens. After running the command, Passport will also create a personal access client and password grant client. Keep track of the generated client IDs and secrets as they will be used for OAuth2 authentication.
Open the app/Providers/AuthServiceProvider.php file and modify the boot() method to include Passport’s routes. This is where you register Passport’s routes for issuing tokens.
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
// Call Passport's routes
Passport::routes();
}
This will allow your application to handle OAuth2 authentication routes.
Now, let’s configure API authentication. In your config/auth.php file, set the api guard to use Passport's token driver. Open the file and update the guards array as follows
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
This tells Laravel to use Passport for API authentication.
You can now protect your API routes with Passport’s auth:api middleware. For example, in routes/api.php, you can define protected routes as follows:
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
This tells Laravel to use Passport for API authentication.
You can now protect your API routes with Passport’s auth:api middleware. For example, in routes/api.php, you can define protected routes as follows:
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
This route is now protected by Passport, and only authenticated users will be able to access it.
To authenticate API requests, you need to generate access tokens. Passport provides the ability to generate personal access tokens for authenticated users. You can issue a token in your controllers or in the Tinker console. First, ensure that your User model is HasApiTokens. Open the app/Models/User.php file and make sure the model uses the HasApiTokens trait:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
To generate a personal access token, you can use the createToken method. For instance, in a controller:
use Illuminate\Http\Request;
use App\Models\User;
public function createToken(Request $request)
{
$user = User::find(1); // Replace with actual user logic
$token = $user->createToken('YourAppName')->accessToken;
return response()->json(['token' => $token]);
}
This will generate a personal access token for the user, which can be used to authenticate API requests.
Now that you have an access token, you can authenticate API requests by passing the token in the Authorization header. Use the Bearer scheme when making requests
curl -X GET "http://your-laravel-app.com/api/user" -H "Authorization: Bearer your-access-token"
If the token is valid, the request will be authorized, and the user’s data will be returned.
If you're building a Single Page Application (SPA) or need to authenticate third-party clients (like mobile apps), you may need to configure Passport for "Authorization Code Grant" or "Password Grant" authentication. You can find detailed instructions in the official Passport documentation. For example, if you're implementing a third-party app, you can generate a client ID and secret via the passport:client command
php artisan passport:client --password
This will generate the necessary credentials for a third-party application to authenticate users via password grant.
To ensure everything is working correctly, test your API endpoints using tools like Postman or Insomnia. Make sure to:
Authorization
header.
Laravel Passport simplifies the process of implementing OAuth2 authentication for your Laravel API applications. In this guide, you learned how to install and set up Passport, configure it for token-based authentication, and protect routes using Passport’s auth:api middleware.
With Laravel Passport, you can securely authenticate API users, generate access tokens, and integrate with third-party applications, all while maintaining the best security practices using OAuth2.
For further customization or advanced features, refer to the official Laravel Passport documentation.