You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

173 lines
8.2 KiB

3 years ago
  1. # CORS Middleware for Laravel
  2. [![Build Status][ico-actions]][link-actions]
  3. [![Software License][ico-license]](LICENSE.md)
  4. [![Total Downloads][ico-downloads]][link-downloads]
  5. Implements https://github.com/asm89/stack-cors for Laravel
  6. ## About
  7. The `laravel-cors` package allows you to send [Cross-Origin Resource Sharing](http://enable-cors.org/)
  8. headers with Laravel middleware configuration.
  9. If you want to have a global overview of CORS workflow, you can browse
  10. this [image](http://www.html5rocks.com/static/images/cors_server_flowchart.png).
  11. ## Upgrading from 0.x / barryvdh-laravel-cors
  12. When upgrading from 0.x versions, there are some breaking changes:
  13. - **A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!**
  14. - **Group middleware is no longer supported, use the global middleware**
  15. - The vendor name has changed (see installation/usage)
  16. - The casing on the props in `cors.php` has 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.
  17. ## Features
  18. * Handles CORS pre-flight OPTIONS requests
  19. * Adds CORS headers to your responses
  20. * Match routes to only add CORS to certain Requests
  21. ## Installation
  22. Require the `fruitcake/laravel-cors` package in your `composer.json` and update your dependencies:
  23. ```sh
  24. composer require fruitcake/laravel-cors
  25. ```
  26. 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:
  27. ```sh
  28. composer remove barryvdh/laravel-cors fruitcake/laravel-cors
  29. composer require fruitcake/laravel-cors
  30. ```
  31. ## Global usage
  32. To allow CORS for all your routes, add the `HandleCors` middleware at the top of the `$middleware` property of `app/Http/Kernel.php` class:
  33. ```php
  34. protected $middleware = [
  35. \Fruitcake\Cors\HandleCors::class,
  36. // ...
  37. ];
  38. ```
  39. Now update the config to define the paths you want to run the CORS service on, (see Configuration below):
  40. ```php
  41. 'paths' => ['api/*'],
  42. ```
  43. ## Configuration
  44. The defaults are set in `config/cors.php`. Publish the config to copy the file to your own config:
  45. ```sh
  46. php artisan vendor:publish --tag="cors"
  47. ```
  48. > **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.
  49. > **Note:** If you are explicitly whitelisting headers, you must include `Origin` or requests will fail to be recognized as CORS.
  50. ### Options
  51. | Option | Description | Default value |
  52. |--------------------------|--------------------------------------------------------------------------|---------------|
  53. | paths | You can enable CORS for 1 or multiple paths, eg. `['api/*'] ` | `[]` |
  54. | allowed_origins | Matches the request origin. Wildcards can be used, eg. `*.mydomain.com` or `mydomain.com:*` | `['*']` |
  55. | allowed_origins_patterns | Matches the request origin with `preg_match`. | `[]` |
  56. | allowed_methods | Matches the request method. | `['*']` |
  57. | allowed_headers | Sets the Access-Control-Allow-Headers response header. | `['*']` |
  58. | exposed_headers | Sets the Access-Control-Expose-Headers response header. | `false` |
  59. | max_age | Sets the Access-Control-Max-Age response header. | `0` |
  60. | supports_credentials | Sets the Access-Control-Allow-Credentials header. | `false` |
  61. `allowed_origins`, `allowed_headers` and `allowed_methods` can be set to `['*']` to accept any value.
  62. > **Note:** For `allowed_origins` you 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 using `allowed_origins_patterns`.
  63. > **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!
  64. > **Note:** Because of [http method overriding](http://symfony.com/doc/current/reference/configuration/framework.html#http-method-override) in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.
  65. > **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 FQDN `app.mydomain.com:8080`
  66. ### Lumen
  67. On Lumen, just register the ServiceProvider manually in your `bootstrap/app.php` file:
  68. ```php
  69. $app->register(Fruitcake\Cors\CorsServiceProvider::class);
  70. ```
  71. Also copy the [cors.php](https://github.com/fruitcake/laravel-cors/blob/master/config/cors.php) config file to `config/cors.php` and put it into action:
  72. ```php
  73. $app->configure('cors');
  74. ```
  75. ## Global usage for Lumen
  76. To allow CORS for all your routes, add the `HandleCors` middleware to the global middleware and set the `paths` property in the config.
  77. ```php
  78. $app->middleware([
  79. // ...
  80. Fruitcake\Cors\HandleCors::class,
  81. ]);
  82. ```
  83. ## Common problems
  84. ### Wrong config
  85. Make sure the `path` option in the config is correct and actually matches the route you are using. Remember to clear the config cache as well.
  86. ### Error handling, Middleware order
  87. 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.
  88. ### Authorization headers / Credentials
  89. 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials) Header to `true`.
  90. ### Echo/die
  91. If you `echo()`, `dd()`, `die()`, `exit()`, `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.
  92. ### Disabling CSRF protection for your API
  93. If possible, use a route group with CSRF protection disabled.
  94. Otherwise you can disable CSRF for certain requests in `App\Http\Middleware\VerifyCsrfToken`:
  95. ```php
  96. protected $except = [
  97. 'api/*',
  98. 'sub.domain.zone' => [
  99. 'prefix/*'
  100. ],
  101. ];
  102. ```
  103. ### Duplicate headers
  104. 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.
  105. ## License
  106. Released under the MIT License, see [LICENSE](LICENSE).
  107. [ico-version]: https://img.shields.io/packagist/v/fruitcake/laravel-cors.svg?style=flat-square
  108. [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
  109. [ico-actions]: https://github.com/fruitcake/laravel-cors/workflows/.github/workflows/run-tests.yml/badge.svg
  110. [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/fruitcake/laravel-cors.svg?style=flat-square
  111. [ico-code-quality]: https://img.shields.io/scrutinizer/g/fruitcake/laravel-cors.svg?style=flat-square
  112. [ico-downloads]: https://img.shields.io/packagist/dt/fruitcake/laravel-cors.svg?style=flat-square
  113. [link-packagist]: https://packagist.org/packages/fruitcake/laravel-cors
  114. [link-actions]: https://github.com/fruitcake/laravel-cors/actions
  115. [link-scrutinizer]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors/code-structure
  116. [link-code-quality]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors
  117. [link-downloads]: https://packagist.org/packages/fruitcake/laravel-cors
  118. [link-author]: https://github.com/fruitcake
  119. [link-contributors]: ../../contributors