Laravel API Authentication is essential when you’re building APIs with Laravel, as securing your endpoints is absolutely necessary. In today’s digital world, APIs are the bridges between applications, but they can also be the weakest link if not properly protected. Laravel, being one of the most popular PHP frameworks, provides multiple ways to secure APIs, and understanding these options is critical for developers looking to build robust, secure applications.
In this guide, we will walk you through everything you need to know about Laravel API authentication. Whether you are beginner or experienced developer, this article will help you to implement the most effective and scalable authentication techniques that Laravel offers.
What Is API Authentication?
API authentication is process of verifying identity of user or system that is attempting to access your API. Without authentication, anyone can access your endpoints, making significant risk for your application.
In Laravel, authentication allows only verified users or systems to make requests, ensuring your data and services stay safe.
Why Laravel for API Development?
Laravel has quickly become favorite for API development due to its:
- Elegant syntax and structure
- Built-in support for RESTful API creation
- Robust authentication packages
- Extensive documentation
- Strong community support
It offers multiple ways for implement authentication, depending on use case, scalability needs, and preferred architecture.
Understanding Laravel Sanctum
Laravel Sanctum is lightweight authentication system built for SPAs (Single Page Applications), mobile applications, and simple token-based APIs.
Key Features:
- Token-based authentication
- CSRF protection
- Easy to use with frontend frameworks like Vue.js or React
- Cookie-based session management for SPAs
How Sanctum Works:
Sanctum generates personal access token for every user. When making API request, the client must include this token in the Authorization header:
Authorization: Bearer your-token-here
When to Use Sanctum:
- If you are building single page application (SPA).
- When you prefer simplicity over complex OAuth flows.
- When you need first party authentication for web applications.
Laravel Passport: OAuth2 Implementation
Laravel Passport provide full OAuth2 server implementation for your Laravel application.
Benefits:
- Handles full OAuth2 flows (Authorization Code, Client Credentials, etc.)
- Great for third party application
- Built on top of League OAuth2 Server
Basic Setup:
Step 1: Install Laravel (If not installed)
- Make sure you have installed Composer. After that install Laravel Installer globally:
composer global require laravel/installer
Make sure ~/.composer/vendor/bin is in your system’s PATH.
Now, create a new Laravel project:
laravel new laravel-backend
cd laravel-backend
Alternatively, you can also use “composer create-project laravel/laravel laravel-backend” command.
Step 2: Install Passport
Install Passport using Composer:
composer require laravel/passport
Step 3: Publish Configuration and Migration Files
php artisan vendor:publish --tag=passport-config
php artisan vendor:publish --tag=passport-migrations
This will publish:
- Passport config file (config/passport.php)
- Migration files for tokens, clients, etc.
Step 4: Run Migrations
php artisan migrate
Step 5: Install Passport
This command creates encryption keys and personal access & password grant clients:
php artisan passport:install
You’ll see output with client ID and secret keys. Please note these down if you use them for testing OAuth2 flows.
Step 6: Configure Authentication Guards
Open config/auth.php, and update the api guard to use passport:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Step 7: Add PassportServiceProvider (for Laravel < 10)
If you’re using Laravel < 10 and it’s not auto-discovered, register it manually in config/app.php:
'providers' => [
Laravel\Passport\PassportServiceProvider::class,
],
Step 8: Enable Passport in AuthServiceProvider
Open app/Providers/AuthServiceProvider.php and add the following in the boot() method:
use Laravel\Passport\Passport;
public function boot()
{
Passport::routes();
}
Step 9: Create API Route in routes/api.php
Route::middleware('auth:api')->group(function () {
Route::get('/user', [ApiController::class, 'getUser']);
});
Step 10: Create the API Controller
Generate the controller:
php artisan make:controller ApiController
Then open “app/Http/Controllers/ApiController.php”:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiController extends Controller
{
public function getUser(Request $request)
{
return response()->json($request->user());
}
}
Step 11: Add API Key to Config
Add API key in config/services.php:
'api_key' => env('API_KEY'),
Then add API key in .env file:
API_KEY=your-secret-api-key
Step 12: Create API Key Middleware
Generate middleware by using below command:
php artisan make:middleware ApiKeyMiddleware
Now open “app/Http/Middleware/ApiKeyMiddleware.php” and add the following:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiKeyMiddleware
{
public function handle(Request $request, Closure $next)
{
$apiKey = $request->header('X-API-KEY');
if ($apiKey !== config('services.api_key')) {
return response()->json(['message' => 'Unauthorized'], 401);
}
return $next($request);
}
}
Step 13: Register Middleware
Open “app/Http/Kernel.php”, and register your middleware:
protected $routeMiddleware = [
// ...
'api.key' => \App\Http\Middleware\ApiKeyMiddleware::class,
];
Step 14: Protect Routes with API Key
In “routes/api.php”:
Route::middleware('api.key')->get('/custom-data', function () {
return ['data' => 'Secured using API Key'];
});
Ideal Use Case:
Laravel Passport is ideal for:
- Third-party app integration (e.g., allow other apps to access your API securely)
- Large-scale applications needing full OAuth2 flows
- Multi-client systems (e.g., web, mobile, desktop clients)
- When you need token scopes, personal access tokens, or authorization codes
JWT Authentication with Laravel
JSON Web Tokens (JWT) is another popular method to securing Laravel APIs.
Why Use JWT?
- Stateless authentication
- Scalable for microservices
- No session storage required
- JWT is a great for distributed systems where sessions are impractical.
Recommended Packages:
- tymon/jwt-auth is the most widely used JWT package for Laravel.
Setup Guide:
Step 1: Install Laravel
If you don’t already have a Laravel project, create one using below command:
composer create-project laravel/laravel jwt-auth-api
cd jwt-auth-api
Step 2: Install JWT Auth Package
Use Composer to install the “tymon/jwt-auth” package:
composer require tymon/jwt-auth
Step 3: Publish Config File
This publishes the JWT config file (config/jwt.php):
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Step 4: Generate JWT Secret
Run below command to generate the JWT secret key and automatically add it to your .env file:
php artisan jwt:secret
Step 5: Update User Model
Open “app/Models/User.php” and implement the JWTSubject interface:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
// ...
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
Step 6: Create AuthController
This controller will handle login, registration, logout, and token refresh.
php artisan make:controller AuthController
Now open “app/Http/Controllers/AuthController.php” and add the following:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('user', 'token'), 201);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
return response()->json(compact('token'));
}
public function logout()
{
JWTAuth::invalidate(JWTAuth::getToken());
return response()->json(['message' => 'Successfully logged out']);
}
public function me()
{
return response()->json(JWTAuth::user());
}
public function refresh()
{
return response()->json([
'token' => JWTAuth::refresh(JWTAuth::getToken())
]);
}
}
Step 7: Define API Routes
Open “routes/api.php” and add the following:
use App\Http\Controllers\AuthController;
Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::post('logout', [AuthController::class, 'logout']);
Route::get('me', [AuthController::class, 'me']);
Route::post('refresh', [AuthController::class, 'refresh']);
});
Step 8: Update auth.php Configuration
Open “config/auth.php” and change the api guard to use jwt:
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Ideal Use Case for JWT
JWT is ideal for:
- APIs used by mobile apps or JavaScript frontends (like React, Vue)
- Single Page Applications (SPAs)
- Decoupled frontend & backend projects
- Microservices communication
- Stateless authentication without server-side sessions
Token vs Session Authentication
Understanding the difference will helps you to make the right decision for your application:
FeatureToken AuthenticationSession AuthenticationStorage | Client-side | Server-side (Laravel sessions)
Feature | Token Authentication | Session Authentication |
---|---|---|
Storage | Client-side | Server-side (Laravel sessions) |
Stateless | Yes | No |
Scalability | High | Medium |
Best For | APIs, mobile apps | Traditional web apps |
For APIs, token-based (Stateless) authentication is typically a better option.
Tip: Always group your sensitive routes under appropriate middleware to prevent unauthorized access.
Best Practices for API Security in Laravel
Here are some rules you can follow for securing your Laravel APIs:
- Always use HTTPS: Prevent token hijacking via man-in-the-middle attacks.
- Validate all inputs: Prevent SQL injection and other common attacks.
- Rate limit your APIs: Use Laravel’s throttle middleware to avoid abuse.
- Keep tokens short-lived: Use refresh tokens where necessary.
- Use strong hashing: Laravel uses Bcrypt/Argon2 for password hashing by default.
- Log suspicious activity: Keep an eye on repeated failed logins or abnormal access.
Common Mistakes and How to Avoid Them
Let’s go over few frequent security slip-ups:
- Storing Tokens in Local Storage: This can expose tokens to XSS attacks. Use HTTP-only cookies instead.
- Not Rotating or Expiring Tokens: Tokens should have limited lifespan. Consider implementing refresh tokens.
- Using Weak Secret Keys: Always generate strong, unique app keys using “php artisan key:generate”.
- Missing CORS Configuration: Unconfigured CORS can open your API to cross-origin attacks. Configure it wisely in cors.php.
Frequently Asked Questions (FAQs)
1. What is the best authentication method for Laravel APIs?
It depends on your project’s needs. If you’re building a single-page application (SPA) or first-party frontend, Laravel Sanctum is best option due to its simplicity. For third-party integrations and complex OAuth2 flows, Laravel Passport is ideal. For stateless, token-based systems, JWT is solid choice.
2. Can I use Sanctum and Passport together in the same Laravel app?
Technically yes, but it’s not recommended. Each is built for different use cases. For simple token-based authentication you can use Sanctum and for full OAuth2-based authentication you can use Passport. Mixing both can lead to complexity and conflicts.
3. Is Sanctum secure enough for production APIs?
Absolutely. Laravel Sanctum is secure for production environments as long as you follow best practices like using HTTPS, setting proper CORS policies, and storing tokens safely (preferably in HTTP-only cookies).
4. What is the difference between Sanctum and Passport in Laravel?
Sanctum is built for mobile apps and SPAs.
Passport is a ised for third-party authentication and it is complete OAuth2 server.
Sanctum is a lightweight and easier to implement, while Passport provides more control and flexibility for advanced use cases.
5. How do I protect Laravel API routes from unauthorized access?
Use middleware like auth:sanctum or auth:api depending on your setup. You can also use Laravel’s policy and gate system to apply role-based access controls on specific endpoints.
Stop Wasting Time on Servers. Start Building Instead.
You didn’t start your project to babysit servers. Let ServerAvatar handle deployment, monitoring, and backups — so you can focus on growth.
Deploy WordPress, Laravel, N8N, and more in minutes. No DevOps required. No command line. No stress.
Trusted by 10,000+ developers and growing.