How to Secure Your Laravel API with Public API Key Middleware

Introduction
Securing your public Laravel API is crucial to prevent unwanted requests and ensure controlled access. One of the best ways to protect your API is by using public API keys with middleware authentication. In this article, we will explore how to secure Laravel public APIs, restrict access, and prevent security threats using API keys and middleware.
By implementing this Laravel API security method, you can allow only authorized users to access your API endpoints. This approach is beneficial for open APIs, subscription-based APIs, and third-party integrations where full user authentication isn’t needed.
Why Use Public API Keys to Secure Laravel API?
Using public API keys in Laravel provides a simple way to restrict access to your REST API. Instead of implementing a full authentication system, you can generate a unique public API key for your users. This method is ideal for:
- Open APIs – Control access without requiring full authentication.
- Subscription-based services – Allow only authorized users.
- Third-party integrations – Enable partners to access your API securely.
- Headless CMS or mobile apps – Protect backend services with API keys.
Step 1: Generate and Distribute Public API Keys
Before applying middleware protection, you need to create unique public API keys. Laravel makes it easy to generate secure random keys using Str::random()
. Run the following code to generate a 32-character API key:
Securely Store and Distribute API Keys
- Store API keys in your database.
- Display them only once to users for security reasons.
- Never expose sensitive API keys in frontend code.
- Rotate keys periodically for enhanced security.
use Illuminate\Support\Str;
$publicApiKey = Str::random(32);
Once generated, distribute these keys to your subscribers securely. They will use this key to access your API.
Step 2: Create Middleware for Public API Key Authentication
To ensure that only requests with a valid public API key can access your Laravel API, you need to create a custom middleware.
Generate Middleware:
Run the following Artisan command to create a new middleware:
php artisan make:middleware ValidatePublicApiKey
Implement the Middleware Logic:
Open the newly created middleware file located at app/Http/Middleware/ValidatePublicApiKey.php and add the following code:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class ValidatePublicApiKey { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { $publicApiKey = env('PUBLIC_API_KEY'); $xApiKey = $request->header('X-API-KEY'); if ($xApiKey !== $publicApiKey) { return response()->json(['message' => 'Unauthenticated'], 401); } return $next($request); } }
In this example, we're checking if the
X-API-KEY
header matches the secret key stored in your application's environment (.env). You can customize this logic to validate against a database or any other storage mechanism.Register the Middleware:
Open Bootstrap/app.php and register your middleware in the withMiddleware function:
use App\Http\Middleware\ValidatePublicApiKey; ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'validate_key' => ValidatePublicApiKey::class, ]); });
Step 3: Apply the Middleware to Your API Routes
To protect specific Laravel API routes, apply the middleware in routes/api.php
:
Route::middleware('validate_key')->group(function () {
Route::prefix('a_products')->group(function () {
Route::get('/', [ProductController::class, 'index'])->name('get-product-list);
});
});
In this example, only requests that include the correct X-API-KEY header will be able to access the /a_products endpoint.
Step 4: Test Your Implementation
Finally, test your implementation by sending a request to the protected endpoint with and without the secret key. You should receive a 401 Unauthenticated response if the key is missing or incorrect.
Use a tool like Postman or cURL to test your API security setup:
Conclusion
By using public API key authentication in Laravel, you can secure your open API endpoints efficiently.
This Laravel security tutorial covers:
✅ Generating secure public API keys
✅ Storing API keys in the database
✅ Creating Laravel middleware for public API key authentication
✅ Applying middleware to protect API routes
✅ Testing Laravel API security with valid and invalid requests
This method is perfect for securing public Laravel APIs, preventing unwanted requests, and improving Laravel API protection without implementing full user authentication.
Additional Resources
🔹 Laravel API Authentication Guide 🔹 Middleware in Laravel 🔹 REST API Security Best Practices
🔹 How to Prevent Sql Injection
Want more Laravel security tips? Bookmark this page and follow for updates!
Get Your Laravel Public API Secure Today!
If you need help securing your Laravel public API, Upwork Laravel developer, or freelance Laravel API developer, feel free to contact me. I specialize in Laravel security, API development, and web application protection.