Last active
February 8, 2024 18:29
-
-
Save shov/080da49891fb5544fe058cd10fcb3730 to your computer and use it in GitHub Desktop.
Laravel middleware to Allow Cross Origin CORS
This file contains 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 Symfony\Component\HttpFoundation\Response; | |
/** | |
* The after middleware to allow specific Access-Control-Allow-Origin | |
*/ | |
class AllowCrossOrigin | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
/** @var Response $response */ | |
$response = $next($request); | |
$allowedOrigins = explode(';', env('ALLOWED_ORIGINS', '')); | |
if (in_array('*', $allowedOrigins)) { | |
$response->headers->set('Access-Control-Allow-Origin', '*'); | |
} else { | |
$origin = $request->headers->get('Origin'); | |
$noPortOrigin = preg_replace('/^(https?)(\:\/\/)([^\:]{1,})(\:[0-9]{0,})?$/', '$1$2$3', $origin); | |
foreach ($allowedOrigins as $allowedOne) { | |
if ($noPortOrigin === $allowedOne) | |
$response->headers->set('Access-Control-Allow-Origin', $origin); | |
} | |
} | |
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, HEAD, PUT, DELETE'); | |
$response->headers->set('Access-Control-Allow-Credentials', 'true'); | |
$response->headers->set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment