Created
March 25, 2020 12:46
-
-
Save manuelgeek/ec187010325f2c64cc1f5241737b54ef to your computer and use it in GitHub Desktop.
Laravel CORS middleware, remember to check and add necessary headers and change the origin accordingly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Support\Facades\Response; | |
class CORS | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$origin = $request->header('origin'); | |
$origin = $origin ?? '*'; | |
// ALLOW OPTIONS METHOD | |
$headers = [ | |
'Access-Control-Allow-Origin' => $origin, | |
'Access-Control-Allow-Methods'=> 'GET, POST, DELETE, PUT, OPTIONS, HEAD, PATCH', | |
'Access-Control-Allow-Headers'=> ' Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Set-Cookie', | |
'Access-Control-Allow-Credentials'=> 'true' | |
]; | |
if($request->getMethod() == "OPTIONS") { | |
// The client-side application can set only headers allowed in Access-Control-Allow-Headers | |
return Response::make('OK', 200, $headers); | |
} | |
$response = $next($request); | |
foreach($headers as $key => $value) { | |
$response->header($key, $value); | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment