Parcourir la source

Adding Middleware CorsHeader

Since nginx messes this horribly up. Here a PHP middleware which handles the task of setting the CorsHeader perfectly!
Ecconia il y a 7 ans
Parent
commit
57b1a71be6
2 fichiers modifiés avec 31 ajouts et 0 suppressions
  1. 2 0
      dist/index.php
  2. 29 0
      middleware/CorsHeader.php

+ 2 - 0
dist/index.php

@@ -1,5 +1,6 @@
 <?php
 	require __DIR__ . '/../vendor/autoload.php';
+	require __DIR__ . '/../middleware/CorsHeader.php';
 
 	use Adepto\Slim3Init\{
 		SlimInit
@@ -8,6 +9,7 @@
 	$slim = new SlimInit();
 	$slim
 		->addHandlersFromDirectory(__DIR__ . '/../handler')
+		->addMiddleware(new CorsHeader(), 'Cors Header')
 		//One of the two preconditions to get more details on requests.
 		//->setDebugHeader('Debug', '1')
 		->run();

+ 29 - 0
middleware/CorsHeader.php

@@ -0,0 +1,29 @@
+<?php
+	use \Psr\Http\Message\{
+		ServerRequestInterface,
+		ResponseInterface
+	};
+
+	class CorsHeader {
+		public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) {
+
+			$method = $_SERVER['REQUEST_METHOD'];
+			$origin = $_SERVER['HTTP_ORIGIN'];
+
+			if(in_array($origin, ['http://localhost:8080', 'https://vv.ecconia.de'])) {
+				header('Access-Control-Allow-Origin: ' . $origin);
+				header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
+				header('Access-Control-Allow-Headers: DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range');
+
+				if($method == 'OPTIONS') {
+					header('Access-Control-Max-Age: 1728000');
+					header('Content-Type: text/plain charset=UTF-8');
+					header('Content-Length: 0');
+
+					return $response->withStatus(204);
+				}
+			}
+
+			return $next($request, $response);
+		}
+	}