Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
Implements https://github.com/asm89/stack-cors for Laravel
laravel-corspackage allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.
If you want to have a global overview of CORS workflow, you can browse this image.
When upgrading from 0.x versions, there are some breaking changes: - A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly! - Group middleware is no longer supported, use the global middleware - The vendor name has changed (see installation/usage) - The casing on the props in
cors.phphas changed from camelCase to snake_case, so if you already have a
cors.phpfile you will need to update the props in there to match the new casing.
fruitcake/laravel-corspackage in your
composer.jsonand update your dependencies:
sh composer require fruitcake/laravel-cors
If you get a conflict, this could be because an older version of barryvdh/laravel-cors or fruitcake/laravel-cors is installed. Remove the conflicting package first, then try install again:
composer remove barryvdh/laravel-cors fruitcake/laravel-cors composer require fruitcake/laravel-cors
To allow CORS for all your routes, add the
HandleCorsmiddleware at the top of the
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:
sh php artisan vendor:publish --tag="cors"
Note: When using custom headers, likeX-Auth-TokenorX-Requested-With, you must set theallowed_headersto include those headers. You can also set it to['*']to allow all custom headers.
Note: If you are explicitly whitelisting headers, you must includeOriginor requests will fail to be recognized as CORS.
| Option | Description | Default value | |--------------------------|--------------------------------------------------------------------------|---------------| | paths | You can enable CORS for 1 or multiple paths, eg.
| | allowedorigins | Matches the request origin. Wildcards can be used, eg.
['*']| | allowedoriginspatterns | Matches the request origin with `pregmatch
| | allowed_methods | Matches the request method. |['']
| | allowed_headers | Sets the Access-Control-Allow-Headers response header. |['']
| | exposed_headers | Sets the Access-Control-Expose-Headers response header. |false
| | max_age | Sets the Access-Control-Max-Age response header. |0
| | supports_credentials | Sets the Access-Control-Allow-Credentials header. |false` |
allowed_methodscan be set to
['*']to accept any value.
Note: Forallowed_originsyou must include the scheme when not using a wildcard, eg.['http://example.com', 'https://example.com']. You must also take into account that the scheme will be present when usingallowed_origins_patterns.
Note: Try to be a specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible!
Note: Because of http method overriding in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.
Note: Sometimes it's necessary to specify the port (when you're coding your app in a local environment for example). You can specify the port or using a wildcard here too, eg.localhost:3000,localhost:*or even using a FQDNapp.mydomain.com:8080
On Lumen, just register the ServiceProvider manually in your
Also copy the cors.php config file to
config/cors.phpand put it into action:
To allow CORS for all your routes, add the
HandleCorsmiddleware to the global middleware and set the
pathsproperty in the config.
$app->middleware([ // ... Fruitcake\Cors\HandleCors::class, ]);
Make sure the
pathoption in the config is correct and actually matches the route you are using. Remember to clear the config cache as well.
Sometimes errors/middleware that return 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 actually works.
If your Request includes an Authorization header or uses Credentials mode, set the
supports_credentialsvalue in the config to true. This will set the Access-Control-Allow-Credentials Header to
dump()etc in your code, you will break the Middleware flow. When output is sent before headers, CORS cannot be added. When the scripts exits before the CORS middleware finished, CORS headers will not be added. Always return a proper response or throw an Exception.
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 .htaccess, nginx or your index.php file, you will get duplicate headers and unexpected results.
Released under the MIT License, see LICENSE.