how can i check laravel api is access by which domain in laravel

To check which domain is accessing your Laravel API, you should inspect the Origin or Referer HTTP headers sent with the request. This is most effectively done using a custom middleware, as these headers are client-provided and can be spoofed, so a central handling point is best for security and control. 

Method 1: Using a Middleware (Recommended for Access Control)

This method allows you to restrict API access to specific domains and is a common practice for security. 

  1. Create a new middleware by running the following Artisan command:bashphp artisan make:middleware CheckApiOrigin
  2. Edit the generated middleware file in app/Http/Middleware/CheckApiOrigin.php to read the incoming headers and enforce your policy.phpnamespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class CheckApiOrigin { public function handle(Request $request, Closure $next): Response { // Get the origin header from the request $origin = $request->header('Origin'); // Get the referer header as a fallback (for non-AJAX or older requests) $referer = $request->header('Referer'); $hostFromReferer = $referer ? parse_url($referer, PHP_URL_HOST) : null; // Define your allowed domains $allowedDomains = ['https://your-frontend-domain.com', 'https://another-allowed-domain.com']; // Check if the origin or referer host is in the allowed list if (!in_array($origin, $allowedDomains) && !in_array($hostFromReferer, $allowedDomains)) { // Optional: Log the unauthorized access attempt \Log::warning('Unauthorized API access attempt from: ' . ($origin ?? $hostFromReferer ?? 'Unknown')); return response('Unauthorized access.', 401); } return $next($request); } }
  3. Register and apply the middleware to your API routes.
    • For all API routes, add the middleware to the api middleware group in bootstrap/app.php (or app/Http/Kernel.php in older Laravel versions):php->withMiddleware(function (Middleware $middleware) { // ... other middleware $middleware->api([ // ... other api middleware \App\Http\Middleware\CheckApiOrigin::class, ]); })
    • Alternatively, apply it to specific routes or route groups in routes/api.php:phpuse App\Http\Middleware\CheckApiOrigin; Route::middleware([CheckApiOrigin::class])->group(function () { // Your protected API routes here });  

Method 2: Accessing Headers Directly in a Controller

You can also access the headers within a controller method for ad-hoc checks, though middleware is cleaner for global policy enforcement.

php

use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function someApiEndpoint(Request $request)
    {
        $origin = $request->header('Origin'); // Get the 'Origin' header value
        $referer = $request->header('Referer'); // Get the 'Referer' header value
        
        // Use the values as needed
        if ($origin === 'https://allowed-domain.com') {
            // Process the request
        } else {
            // Deny access
            return response('Unauthorized', 401);
        }
    }
}

Security Considerations

  • Header Spoofing: Remember that the Origin and Referer headers are sent by the client and can be manually faked with tools like cURL.
  • API Keys/Tokens: For robust security, domain checking should be used in conjunction with a more secure authentication mechanism like API tokens, OAuth2 (using Laravel Passport or Laravel Sanctum), or a combination of both.



Leave a Reply