diff --git a/readme.md b/readme.md index 4667631..dbcb04b 100644 --- a/readme.md +++ b/readme.md @@ -75,6 +75,10 @@ Require the `barryvdh/laravel-cors` package in your composer.json and update you Add the CorsServiceProvider to your app/config/app.php providers array: 'Barryvdh\Cors\CorsServiceProvider', + +For Laravel 5.x, you need to add the Middleware to your App Kernel: + + 'Barryvdh\Cors\Middleware\HandleCors', Publish the config file to create your own configuration: diff --git a/src/CorsServiceProvider.php b/src/CorsServiceProvider.php index 84d7dc7..8ac9a7a 100644 --- a/src/CorsServiceProvider.php +++ b/src/CorsServiceProvider.php @@ -1,8 +1,7 @@ app['request']; - if (!$request->headers->has('Origin') || $request->headers->get('Origin') == $request->getSchemeAndHttpHost()) { - return; - } $this->app['config']->package('barryvdh/laravel-cors', realpath(__DIR__ . '/config')); - $this->app->middleware('Asm89\Stack\Cors', array($this->getOptions($request))); + + if ($this->checkVersion('5.0-dev', '<')) { + if ($request->headers->has('Origin') && $request->headers->get('Origin') !== $request->getSchemeAndHttpHost()) { + $this->app->middleware('Asm89\Stack\Cors', array($this->getOptions($request))); + } + } else { + $this->app->bind('Asm89\Stack\CorsService', function() use($request){ + return new CorsService($this->getOptions($request)); + }); + } } /** @@ -102,8 +107,18 @@ protected function normalizeOptions($options) } } return $options; - } + /** + * Compare the current Laravel version + * + * @param $version + * @param null $operator + * @return mixed + */ + protected function checkVersion($version, $operator = null) + { + return version_compare($this->app->version(), $version, $operator); + } -} \ No newline at end of file +} diff --git a/src/Middleware/HandleCors.php b/src/Middleware/HandleCors.php new file mode 100644 index 0000000..22196ef --- /dev/null +++ b/src/Middleware/HandleCors.php @@ -0,0 +1,47 @@ +cors = $cors; + } + + /** + * Handle an incoming request. Based on Asm89\Stack\Cors by asm89 + * @see https://github.com/asm89/stack-cors/blob/master/src/Asm89/Stack/Cors.php + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + if ( + ! $this->cors->isCorsRequest($request) + || $request->headers->get('Origin') == $request->getSchemeAndHttpHost() + ) { + return $next($request); + } + + if ($this->cors->isPreflightRequest($request)) { + return $this->cors->handlePreflightRequest($request); + } + + if ( ! $this->cors->isActualRequestAllowed($request)) { + return new Response('Not allowed.', 403); + } + + $response = $next($request); + + return $this->cors->addActualRequestHeaders($response, $request); + } +}