├── LICENSE ├── composer.json ├── config └── cors.php ├── readme.md └── src ├── CorsServiceProvider.php └── HandleCors.php /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013-2016 Barry vd. Heuvel 2 | 3 | Copyright for portions of this project are held by [asm89 (Alexander)] as part of project asm89/stack-cors. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is furnished 10 | to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fruitcake/laravel-cors", 3 | "description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application", 4 | "keywords": ["laravel", "cors", "crossdomain", "api"], 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Fruitcake", 9 | "homepage": "https://fruitcake.nl" 10 | }, 11 | { 12 | "name": "Barry vd. Heuvel", 13 | "email": "barryvdh@gmail.com" 14 | } 15 | ], 16 | "require": { 17 | "php": "^7.4|^8.0", 18 | "illuminate/support": "^6|^7|^8|^9", 19 | "illuminate/contracts": "^6|^7|^8|^9", 20 | "fruitcake/php-cors": "^1.2" 21 | }, 22 | "require-dev": { 23 | "laravel/framework": "^6|^7.24|^8", 24 | "phpunit/phpunit": "^9", 25 | "squizlabs/php_codesniffer": "^3.5", 26 | "orchestra/testbench-dusk": "^4|^5|^6|^7" 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "Fruitcake\\Cors\\": "src/" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Fruitcake\\Cors\\Tests\\": "tests/" 36 | } 37 | }, 38 | "extra": { 39 | "branch-alias": { 40 | "dev-master": "3.0-dev" 41 | }, 42 | "laravel": { 43 | "providers": [ 44 | "Fruitcake\\Cors\\CorsServiceProvider" 45 | ] 46 | } 47 | }, 48 | "scripts": { 49 | "test": "phpunit", 50 | "check-style": "phpcs -p --standard=psr12 src/", 51 | "fix-style": "phpcbf -p --standard=psr12 src/" 52 | }, 53 | "minimum-stability": "dev" 54 | } 55 | -------------------------------------------------------------------------------- /config/cors.php: -------------------------------------------------------------------------------- 1 | [], 25 | 26 | /* 27 | * Matches the request method. `['*']` allows all methods. 28 | */ 29 | 'allowed_methods' => ['*'], 30 | 31 | /* 32 | * Matches the request origin. `['*']` allows all origins. Wildcards can be used, eg `*.mydomain.com` 33 | */ 34 | 'allowed_origins' => ['*'], 35 | 36 | /* 37 | * Patterns that can be used with `preg_match` to match the origin. 38 | */ 39 | 'allowed_origins_patterns' => [], 40 | 41 | /* 42 | * Sets the Access-Control-Allow-Headers response header. `['*']` allows all headers. 43 | */ 44 | 'allowed_headers' => ['*'], 45 | 46 | /* 47 | * Sets the Access-Control-Expose-Headers response header with these headers. 48 | */ 49 | 'exposed_headers' => [], 50 | 51 | /* 52 | * Sets the Access-Control-Max-Age response header when > 0. 53 | */ 54 | 'max_age' => 0, 55 | 56 | /* 57 | * Sets the Access-Control-Allow-Credentials header. 58 | */ 59 | 'supports_credentials' => false, 60 | ]; 61 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # CORS Middleware for Laravel 2 | 3 | [![Build Status][ico-actions]][link-actions] 4 | [![Latest Stable Version](https://poser.pugx.org/fruitcake/laravel-cors/version.png)](https://packagist.org/packages/fruitcake/laravel-cors) 5 | [![Software License][ico-license]](LICENSE.md) 6 | [![Total Downloads][ico-downloads]][link-downloads] 7 | [![Fruitcake](https://img.shields.io/badge/Powered%20By-Fruitcake-b2bc35.svg)](https://fruitcake.nl/) 8 | 9 | Implements https://github.com/fruitcake/php-cors for Laravel 10 | 11 | ## Note for users upgrading to Laravel 9, 10 or higher 12 | ### This package is deprecated because all supported Laravel versions now include the CORS middleware in the core. 13 | 14 | Since Laravel 9.2, this Middleware is included in laravel/framework. You can use the provided middleware, which should be compatible with the Middleware and config provided in this package. See https://github.com/laravel/laravel/pull/5825/files for the changes. 15 | 16 | Steps to upgrade: 17 | 1. Remove `"fruitcake/laravel-cors"` from your composer.json 18 | 2. Replace `\Fruitcake\Cors\HandleCors::class,` with `\Illuminate\Http\Middleware\HandleCors::class,` in `app/Http/Kernel.php` 19 | 20 | See `https://github.com/fruitcake/php-cors` for advanced usage. The config stays the same. 21 | 22 | ## About 23 | 24 | The `laravel-cors` package allows you to send [Cross-Origin Resource Sharing](http://enable-cors.org/) 25 | headers with Laravel middleware configuration. 26 | 27 | If you want to have a global overview of CORS workflow, you can browse 28 | this [image](http://www.html5rocks.com/static/images/cors_server_flowchart.png). 29 | 30 | ## Upgrading from 0.x (barryvdh/laravel-cors) 31 | When upgrading from 0.x versions, there are some breaking changes: 32 | - **A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!** 33 | - **Group middleware is no longer supported, use the global middleware** 34 | - The vendor name has changed (see installation/usage) 35 | - 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. 36 | 37 | ## Features 38 | 39 | * Handles CORS pre-flight OPTIONS requests 40 | * Adds CORS headers to your responses 41 | * Match routes to only add CORS to certain Requests 42 | 43 | ## Installation 44 | 45 | Require the `fruitcake/laravel-cors` package in your `composer.json` and update your dependencies: 46 | ```sh 47 | composer require fruitcake/laravel-cors 48 | ``` 49 | 50 | 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: 51 | 52 | ```sh 53 | composer remove barryvdh/laravel-cors fruitcake/laravel-cors 54 | composer require fruitcake/laravel-cors 55 | ``` 56 | 57 | ## Global usage 58 | 59 | To allow CORS for all your routes, add the `HandleCors` middleware at the top of the `$middleware` property of `app/Http/Kernel.php` class: 60 | 61 | ```php 62 | protected $middleware = [ 63 | \Fruitcake\Cors\HandleCors::class, 64 | // ... 65 | ]; 66 | ``` 67 | 68 | Now update the config to define the paths you want to run the CORS service on, (see Configuration below): 69 | 70 | ```php 71 | 'paths' => ['api/*'], 72 | ``` 73 | 74 | ## Configuration 75 | 76 | The defaults are set in `config/cors.php`. Publish the config to copy the file to your own config: 77 | ```sh 78 | php artisan vendor:publish --tag="cors" 79 | ``` 80 | > **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. 81 | 82 | > **Note:** If you are explicitly whitelisting headers, you must include `Origin` or requests will fail to be recognized as CORS. 83 | 84 | 85 | ### Options 86 | 87 | | Option | Description | Default value | 88 | |--------------------------|--------------------------------------------------------------------------|---------------| 89 | | paths | You can enable CORS for 1 or multiple paths, eg. `['api/*'] ` | `[]` | 90 | | allowed_methods | Matches the request method. | `['*']` | 91 | | allowed_origins | Matches the request origin. Wildcards can be used, eg. `*.mydomain.com` or `mydomain.com:*` | `['*']` | 92 | | allowed_origins_patterns | Matches the request origin with `preg_match`. | `[]` | 93 | | allowed_headers | Sets the Access-Control-Allow-Headers response header. | `['*']` | 94 | | exposed_headers | Sets the Access-Control-Expose-Headers response header. | `[]` | 95 | | max_age | Sets the Access-Control-Max-Age response header. | `0` | 96 | | supports_credentials | Sets the Access-Control-Allow-Credentials header. | `false` | 97 | 98 | 99 | `allowed_origins`, `allowed_headers` and `allowed_methods` can be set to `['*']` to accept any value. 100 | 101 | > **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`. 102 | 103 | > **Note:** Try to be as specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible! 104 | 105 | > **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. 106 | 107 | > **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` 108 | 109 | ### Lumen 110 | 111 | On Lumen, just register the ServiceProvider manually in your `bootstrap/app.php` file: 112 | 113 | ```php 114 | $app->register(Fruitcake\Cors\CorsServiceProvider::class); 115 | ``` 116 | 117 | 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: 118 | 119 | ```php 120 | $app->configure('cors'); 121 | ``` 122 | 123 | ## Global usage for Lumen 124 | 125 | To allow CORS for all your routes, add the `HandleCors` middleware to the global middleware and set the `paths` property in the config. 126 | 127 | ```php 128 | $app->middleware([ 129 | // ... 130 | Fruitcake\Cors\HandleCors::class, 131 | ]); 132 | ``` 133 | 134 | ## Common problems 135 | 136 | ### Wrong config 137 | 138 | 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. 139 | 140 | ### Error handling, Middleware order 141 | 142 | 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. 143 | 144 | ### Authorization headers / Credentials 145 | 146 | 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`. 147 | 148 | ### Echo/die 149 | 150 | If you use `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 script exits before the CORS middleware finishes, CORS headers will not be added. Always return a proper response or throw an Exception. 151 | 152 | ### Disabling CSRF protection for your API 153 | 154 | If possible, use a route group with CSRF protection disabled. 155 | Otherwise you can disable CSRF for certain requests in `App\Http\Middleware\VerifyCsrfToken`: 156 | 157 | ```php 158 | protected $except = [ 159 | 'api/*', 160 | 'sub.domain.zone' => [ 161 | 'prefix/*' 162 | ], 163 | ]; 164 | ``` 165 | 166 | ### Duplicate headers 167 | 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. 168 | 169 | ### No Cross-Site requests 170 | If you are not doing Cross-Site requests, meaning if you are not requesting site-a.com/api from site-b.com, your browser will not send the `Origin: https://site-b.com` request header, CORS will be "disabled" as the `Access-Control-Allow-Origin` header will be also missing. This happens because requests are being dispatched from the same and no protection is needed in this case. 171 | 172 | ## License 173 | 174 | Released under the MIT License, see [LICENSE](LICENSE). 175 | 176 | [ico-version]: https://img.shields.io/packagist/v/fruitcake/laravel-cors.svg?style=flat-square 177 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 178 | [ico-actions]: https://github.com/fruitcake/laravel-cors/actions/workflows/run-tests.yml/badge.svg 179 | [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/fruitcake/laravel-cors.svg?style=flat-square 180 | [ico-code-quality]: https://img.shields.io/scrutinizer/g/fruitcake/laravel-cors.svg?style=flat-square 181 | [ico-downloads]: https://img.shields.io/packagist/dt/fruitcake/laravel-cors.svg?style=flat-square 182 | 183 | [link-packagist]: https://packagist.org/packages/fruitcake/laravel-cors 184 | [link-actions]: https://github.com/fruitcake/laravel-cors/actions 185 | [link-scrutinizer]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors/code-structure 186 | [link-code-quality]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors 187 | [link-downloads]: https://packagist.org/packages/fruitcake/laravel-cors 188 | [link-author]: https://github.com/fruitcake 189 | [link-contributors]: ../../contributors 190 | -------------------------------------------------------------------------------- /src/CorsServiceProvider.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom($this->configPath(), 'cors'); 21 | 22 | $this->app->singleton(CorsService::class, function ($app) { 23 | return new CorsService($this->app['config']->get('cors')); 24 | }); 25 | } 26 | 27 | /** 28 | * Register the config for publishing 29 | * 30 | */ 31 | public function boot() 32 | { 33 | if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { 34 | $this->publishes([$this->configPath() => config_path('cors.php')], 'cors'); 35 | } elseif ($this->app instanceof LumenApplication) { 36 | $this->app->configure('cors'); 37 | } 38 | } 39 | 40 | /** 41 | * Set the config path 42 | * 43 | * @return string 44 | */ 45 | protected function configPath() 46 | { 47 | return __DIR__ . '/../config/cors.php'; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/HandleCors.php: -------------------------------------------------------------------------------- 1 | cors = $cors; 24 | $this->container = $container; 25 | } 26 | 27 | /** 28 | * Handle an incoming request. Based on Asm89\Stack\Cors by asm89 29 | * 30 | * @param \Illuminate\Http\Request $request 31 | * @param \Closure $next 32 | * @return Response 33 | */ 34 | public function handle($request, Closure $next) 35 | { 36 | // Check if we're dealing with CORS and if we should handle it 37 | if (! $this->shouldRun($request)) { 38 | return $next($request); 39 | } 40 | 41 | // For Preflight, return the Preflight response 42 | if ($this->cors->isPreflightRequest($request)) { 43 | $response = $this->cors->handlePreflightRequest($request); 44 | 45 | $this->cors->varyHeader($response, 'Access-Control-Request-Method'); 46 | 47 | return $response; 48 | } 49 | 50 | 51 | // Handle the request 52 | $response = $next($request); 53 | 54 | if ($request->getMethod() === 'OPTIONS') { 55 | $this->cors->varyHeader($response, 'Access-Control-Request-Method'); 56 | } 57 | 58 | return $this->addHeaders($request, $response); 59 | } 60 | 61 | /** 62 | * Add the headers to the Response, if they don't exist yet. 63 | * 64 | * @param Request $request 65 | * @param Response $response 66 | * @return Response 67 | */ 68 | protected function addHeaders(Request $request, Response $response): Response 69 | { 70 | if (! $response->headers->has('Access-Control-Allow-Origin')) { 71 | // Add the CORS headers to the Response 72 | $response = $this->cors->addActualRequestHeaders($response, $request); 73 | } 74 | 75 | return $response; 76 | } 77 | 78 | /** 79 | * Add the headers to the Response, if they don't exist yet. 80 | * 81 | * @param RequestHandled $event 82 | * @deprecated 83 | */ 84 | public function onRequestHandled(RequestHandled $event) 85 | { 86 | if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) { 87 | $this->addHeaders($event->request, $event->response); 88 | } 89 | } 90 | 91 | 92 | /** 93 | * Determine if the request has a URI that should pass through the CORS flow. 94 | * 95 | * @param \Illuminate\Http\Request $request 96 | * @return bool 97 | */ 98 | protected function shouldRun(Request $request): bool 99 | { 100 | return $this->isMatchingPath($request); 101 | } 102 | 103 | /** 104 | * The the path from the config, to see if the CORS Service should run 105 | * 106 | * @param \Illuminate\Http\Request $request 107 | * @return bool 108 | */ 109 | protected function isMatchingPath(Request $request): bool 110 | { 111 | // Get the paths from the config or the middleware 112 | $paths = $this->getPathsByHost($request->getHost()); 113 | 114 | foreach ($paths as $path) { 115 | if ($path !== '/') { 116 | $path = trim($path, '/'); 117 | } 118 | 119 | if ($request->fullUrlIs($path) || $request->is($path)) { 120 | return true; 121 | } 122 | } 123 | 124 | return false; 125 | } 126 | 127 | /** 128 | * Paths by given host or string values in config by default 129 | * 130 | * @param string $host 131 | * @return array 132 | */ 133 | protected function getPathsByHost(string $host) 134 | { 135 | $paths = $this->container['config']->get('cors.paths', []); 136 | // If where are paths by given host 137 | if (isset($paths[$host])) { 138 | return $paths[$host]; 139 | } 140 | // Defaults 141 | return array_filter($paths, function ($path) { 142 | return is_string($path); 143 | }); 144 | } 145 | } 146 | --------------------------------------------------------------------------------