Cross-Origin Resource Sharing (CORS) is an HTTP-header-based mechanism that enables a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, to check that the server will allow the actual request. In that preflight, the browser sends headers that show the HTTP method and headers that will be used in the actual request.
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.
The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration. If you want to have a global overview of the CORS workflow, you can browse this image.
When upgrading from 0.x versions, there are some breaking changes:
cors.phphas changed from camelCase to snake_case, so if you already have a cors.php file you will need to update the props in there to match the new casing.
For the installation, You've to require the
fruitcake/laravel-cors package in your
composer.json and update your dependencies:
composer require fruitcake/laravel-cors
If you get a conflict, this could be because an older version of
fruitcake/laravel-cors is installed. Remove the conflicting package first, then try the install again:
composer remove barryvdh/laravel-cors fruitcake/laravel-cors composer require fruitcake/laravel-cors'
To allow CORS for all your routes, add the HandleCors middleware at the top of the
$middleware property of
protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... ];
Now update the config to define the paths you want to run the CORS service on, (see Configuration below):
'paths' => ['api/*'],
The defaults are set in
config/cors.php. Publish the
config to copy the file to your own config:
php artisan vendor:publish --tag="cors"
Note: When using custom headers, like X-Auth-Token or X-Requested-With, you must set the allowed_headers to include those headers. You can also set it to ['*'] to allow all custom headers.
Note: If you are explicitly whitelisting headers, you must include Origin or requests will fail to be recognized as CORS.
Make sure the path option in the config is correct and matches the route you are using. Remember to clear the config cache as well.
Error handling, Middleware order
errors/middleware that return their own responses can prevent the CORS Middleware from being run. Try changing the order of the Middleware and make sure it's the first entry in the global middleware, not a route group. Also check your logs for actual errors, because without CORS, the errors will be swallowed by the browser, only showing CORS errors. Also, try running it without CORS to make sure it works.
Authorization headers / Credentials
If your Request includes an Authorization header or uses Credentials mode, set the supports_credentials value in the config to true. This will set the Access-Control-Allow-Credentials Header to true.
dump() etc in your code, you will break the Middleware flow. When the output is sent before headers, CORS cannot be added. When the scripts exit before the CORS middleware is finished, CORS headers will not be added. Always return a proper response or throw an Exception.
Disabling CSRF protection for your API
If possible, use a route group with CSRF protection disabled. Otherwise, you can disable CSRF for certain requests in
protected $except = [ 'api/*', 'sub.domain.zone' => [ 'prefix/*' ], ];
The CORS Middleware should be the only place you add these headers. If you also add headers in
Nginx, or your
index.php file, you will get duplicate headers and unexpected results.
For more details, You can visit its complete documentation on Github.
Published at : 22-11-2021
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.