To protect your client microservice endpoints using Laravel Passport, you can implement a middleware that verifies the validity of the access token. Here's a step-by-step guide on how to achieve this:
-
Use Passport's Token Middleware: Laravel Passport provides a middleware called
auth:apithat you can use to protect your routes. This middleware will automatically check the validity of the access token against the Passport server. -
Set Up Middleware in Your Routes: Apply the
auth:apimiddleware to the routes you want to protect. This will ensure that only requests with a valid access token can access these routes.Route::middleware('auth:api')->group(function () { Route::get('/invoices', 'InvoiceController@index'); // Add other protected routes here }); -
Token Caching (Optional): To mitigate performance issues due to frequent token validation requests to the auth server, you can implement token caching. This involves storing the token validation result temporarily and reusing it for subsequent requests within a short time frame.
Here's a basic example of how you might implement token caching:
use Illuminate\Support\Facades\Cache; use Laravel\Passport\TokenRepository; class CheckTokenMiddleware { protected $tokens; public function __construct(TokenRepository $tokens) { $this->tokens = $tokens; } public function handle($request, Closure $next) { $token = $request->bearerToken(); if (!$token) { return response()->json(['error' => 'Unauthorized'], 401); } $cacheKey = 'token_validity_' . $token; $isValid = Cache::remember($cacheKey, 60, function () use ($token) { return $this->tokens->findValidToken($request->user(), $token) !== null; }); if (!$isValid) { return response()->json(['error' => 'Unauthorized'], 401); } return $next($request); } }In this example, the token validity is cached for 60 seconds. Adjust the caching duration based on your application's needs.
-
Register Middleware: Register your custom middleware in the
app/Http/Kernel.phpfile if you choose to implement token caching or any custom logic.protected $routeMiddleware = [ // Other middleware 'check.token' => \App\Http\Middleware\CheckTokenMiddleware::class, ]; -
Apply Custom Middleware: If you created a custom middleware, apply it to your routes:
Route::middleware('check.token')->group(function () { Route::get('/invoices', 'InvoiceController@index'); // Add other protected routes here });
By following these steps, you can ensure that your client microservice endpoints are protected and only accessible with valid access tokens, while also optimizing performance with token caching.