For Laravel Framework you can specify the allowed domains, for example in the CORS middleware:
app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class Cors
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (!method_exists($response, 'header')) {
return $response;
}
$allowedOrigins = [
'http://localhost:8000',
'http://localhost:8080',
'https://app.example.com',
'https://example.com',
];
if (in_array($request->header('origin'), $allowedOrigins)) {
$origin = $request->header('origin');
} else {
return $response;
}
return $response
->header('Access-Control-Allow-Origin', $origin)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
->header('Access-Control-Max-Age', '86400');
}
}
Or you can use an Origin request:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class Cors
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (!method_exists($response, 'header')) {
return $response;
}
$origin = $request->header('origin');
return $response
->header('Access-Control-Allow-Origin', $origin)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
->header('Access-Control-Max-Age', '86400');
}
}
Then register it in app/Http/Kernel.php
protected $routeMiddleware = [
...
'cors' => \App\Http\Middleware\Cors::class,
];
And finally, use whatever you need on any routes:
Route::group(['middleware' => ['auth', 'cors']], function () {
...
Route::get('/profile', [ProfileController::class, 'index']);
});
Access-Control-Allow-Origin
header does not mean that other domains cannot trigger a method on this endpoint (e.g. REST API method). It just means that disallowed origins cannot use the result in javascript (browser ensures this). For restricting access to an endpoint for specific domains use a server-side request filter that e.g. returns HTTP 401 for disallowed domains.Vary: Origin
header when you want to use multiple URLs, see: fetch.spec.whatwg.org/#cors-protocol-and-http-caches