Hi there! If you’re building a web application with Laravel 12, you might be wondering how to keep it secure, especially when it comes to user authentication. I’ve been working with Laravel for a while, and one of the best ways to secure your app is by using OAuth authentication.
OAuth is a powerful and widely-used protocol that allows secure API access without sharing user credentials. In this article, I’ll walk you through the process of setting up OAuth authentication in your Laravel 12 app using Laravel Passport, a popular package for implementing OAuth 2.0.
Here’s a clear, beginner-friendly guide to setting up OAuth authentication in your Laravel 12 application using Laravel Passport.
First, I need a fresh Laravel 12 project to work with. If you haven’t already installed Laravel 12, you can create a new project using Composer. Open your terminal and run:
composer create-project laravel/laravel oauth-app
cd oauth-app
This sets up a new Laravel project named oauth-app
. Make sure you have PHP 8.2 or higher and Composer installed.
Laravel Passport is a fantastic package that makes implementing OAuth 2.0 super easy. To install it, run the following command in your project directory:
composer require laravel/passport
Once installed, I need to run the migration to create the necessary database tables for Passport. These tables will store OAuth clients, tokens, and scopes. Run:
php artisan migrate
Next, I’ll install Passport’s components by running:
php artisan passport:install
This command generates encryption keys and creates default OAuth clients (a personal access client and a password grant client).
Now, I’ll configure Passport in my Laravel app. Open the app/Providers/AuthServiceProvider.php
file and add the following line to the boot
method:
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
This registers Passport’s routes for handling OAuth requests, such as issuing tokens.
Next, I need to tell Laravel to use Passport for API authentication. Open config/auth.php
and update the guards
section to use the api
driver with Passport:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
I need to ensure my User
model is ready for Passport. Open app/Models/User.php
and make sure it implements the HasApiTokens
trait:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
protected $fillable = [
'name', 'email', 'password',
];
}
This trait provides methods for managing API tokens.
Let’s create a simple API endpoint to test our OAuth authentication. Open routes/api.php
and add a protected route:
use Illuminate\Support\Facades\Auth;
Route::middleware('auth:api')->get('/user', function () {
return Auth::user();
});
This route returns the authenticated user’s details but only if a valid OAuth token is provided.
To test OAuth, I need to create an OAuth client. Run the following Artisan command to create a password grant client:
php artisan passport:client --password
Follow the prompts to name your client (e.g., “My App Client”). The command will output a Client ID
and Client Secret
. Save these, as you’ll need them to request tokens.
Now, I’ll test the authentication flow using a tool like Postman. First, I need to request an access token using the password grant type. Send a POST request to:
http://your-app.test/oauth/token
Include the following parameters in the request body (form-data):
grant_type
: passwordclient_id
: [Your Client ID]client_secret
: [Your Client Secret]username
: [User’s email]password
: [User’s password]scope
: [Leave empty for now]If successful, you’ll receive a JSON response with an access_token
. Use this token to access the protected /user
endpoint. In Postman, send a GET request to:
http://your-app.test/api/user
Add the Authorization
header with the value Bearer [your_access_token]
. You should see the authenticated user’s details in the response.
To secure other API routes, simply apply the auth:api
middleware. For example, in routes/api.php
:
Route::middleware('auth:api')->get('/secure-data', function () {
return response()->json(['message' => 'This is secure data!']);
});
This ensures only authenticated users with valid tokens can access the route.
Implementing OAuth authentication in my Laravel 12 app was easier than I thought, thanks to Laravel Passport! By following these steps, I’ve added a robust layer of security to my API, ensuring that only authorized users can access protected resources. OAuth 2.0 is a powerful standard, and with Passport, Laravel makes it straightforward to implement. Whether you’re building a mobile app backend or a web API, this setup will keep your application secure and scalable.
Q1: What is OAuth 2.0, and why should I use it in Laravel?
A: OAuth 2.0 is a protocol that allows secure API access without sharing user credentials. It’s great for Laravel apps because it provides a standardized way to authenticate users for APIs, ensuring security and scalability.
Q2: What’s the difference between Laravel Passport and Sanctum?
A: Laravel Passport is designed for OAuth 2.0, ideal for complex API authentication with clients like mobile apps. Sanctum is lighter and better suited for simpler token-based authentication, like SPAs or mobile apps.
Q3: Do I need a package like Passport for OAuth?
A: While you can implement OAuth manually, Passport simplifies the process by providing ready-to-use tools for token management, client creation, and more.
Q4: How do I revoke an OAuth token?
A: You can revoke a token by calling $user->token()->revoke()
on the authenticated user’s token. This invalidates the token, preventing further use.
Q5: Is Laravel Passport secure for production?
A: Yes, Passport is secure for production when configured properly. Ensure you use HTTPS, protect your client secrets, and regularly rotate encryption keys.
You might also like :