I’m trying to move the Slim4 Cors example into a Middleware class.
(src/Application/Middleware/CorsMiddleware.php)
<?php
declare(strict_types=1);
namespace App\Application\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;
class CorsMiddleware implements Middleware
{
/**
* {@inheritdoc}
*/
public function process(Request $request, RequestHandler $handler): Response
{
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
$methods = $routingResults->getAllowedMethods();
$requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
$response = $handler->handle($request);
$response = $response->withHeader('Access-Control-Allow-Origin', 'http://lxd-webserver');
$response = $response->withHeader('Access-Control-Allow-Methods', implode(',', $methods));
$response = $response->withHeader('Access-Control-Allow-Headers', $requestHeaders);
// Optional: Allow Ajax CORS requests with Authorization header
$response = $response->withHeader('Access-Control-Allow-Credentials', 'false');
error_log(print_r("CorsMiddleware",true));
error_log(print_r($response,true));
return $response;
}
}
and then I thought to put it here in routes.php:
<?php
declare(strict_types=1);
use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use App\Application\Middleware\CorsMiddleware;
use Psr\Log\LoggerInterface;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;
use Slim\Exception\HttpNotFoundException;
return function (App $app) {
$container = $app->getContainer();
$app->options('/{routes:.*}', function (Request $request, Response $response) use ($container) {
// CORS Pre-Flight OPTIONS Request Handler
return $response;
})->add(new CorsMiddleware());
$app->add(function ($request, $handler) use ($container) {
$response = $handler->handle($request);
// https://discourse.slimframework.com/t/solved-slim-4-skeleton-logging-to-app-log/3448/2
$logger = $container->get(LoggerInterface::class);
$method = $request->getMethod();
$url = (string)$request->getUri();
$logger->info(sprintf('%s %s', $method, $url));
return $response;
})->add(new CorsMiddleware());
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello world!');
error_log(print_r("Hello Wolrd",true));
error_log(print_r($response,true));
return $response;
})->setName('root');
$app->group('/users', function (Group $group) {
$group->get('', ListUsersAction::class);
$group->get('/{id}', ViewUserAction::class);
});
/**
* Catch-all route to serve a 404 Not Found page if none of the routes match
* NOTE: make sure this route is defined last
*/
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function ($request, $response) {
throw new HttpNotFoundException($request);
});
};
The Cors Middleware gets called, as logged here:
[15-Jan-2021 19:55:51 Europe/Berlin] Hello Wolrd
[15-Jan-2021 19:55:51 Europe/Berlin] Slim\Psr7\Response Object
(
[status:protected] => 200
[reasonPhrase:protected] =>
[protocolVersion:protected] => 1.1
[headers:protected] => Slim\Psr7\Headers Object
(
[globals:protected] => Array
(
)
[headers:protected] => Array
(
)
)
[body:protected] => Slim\Psr7\Stream Object
(
[stream:protected] => Resource id #8
[meta:protected] => Array
(
[wrapper_type] => PHP
[stream_type] => TEMP
[mode] => w+b
[unread_bytes] => 0
[seekable] => 1
[uri] => php://temp
)
[readable:protected] =>
[writable:protected] => 1
[seekable:protected] =>
[size:protected] =>
[isPipe:protected] =>
[finished:protected] =>
[cache:protected] =>
)
)
[15-Jan-2021 19:55:51 Europe/Berlin] CorsMiddleware
[15-Jan-2021 19:55:51 Europe/Berlin] Slim\Psr7\Response Object
(
[status:protected] => 200
[reasonPhrase:protected] =>
[protocolVersion:protected] => 1.1
[headers:protected] => Slim\Psr7\Headers Object
(
[globals:protected] => Array
(
)
[headers:protected] => Array
(
[access-control-allow-origin] => Slim\Psr7\Header Object
(
[originalName:Slim\Psr7\Header:private] => Access-Control-Allow-Origin
[normalizedName:Slim\Psr7\Header:private] => access-control-allow-origin
[values:Slim\Psr7\Header:private] => Array
(
[0] => http://lxd-webserver
)
)
[access-control-allow-methods] => Slim\Psr7\Header Object
(
[originalName:Slim\Psr7\Header:private] => Access-Control-Allow-Methods
[normalizedName:Slim\Psr7\Header:private] => access-control-allow-methods
[values:Slim\Psr7\Header:private] => Array
(
[0] => GET,OPTIONS
)
)
[access-control-allow-headers] => Slim\Psr7\Header Object
(
[originalName:Slim\Psr7\Header:private] => Access-Control-Allow-Headers
[normalizedName:Slim\Psr7\Header:private] => access-control-allow-headers
[values:Slim\Psr7\Header:private] => Array
(
[0] =>
)
)
[access-control-allow-credentials] => Slim\Psr7\Header Object
(
[originalName:Slim\Psr7\Header:private] => Access-Control-Allow-Credentials
[normalizedName:Slim\Psr7\Header:private] => access-control-allow-credentials
[values:Slim\Psr7\Header:private] => Array
(
[0] => false
)
)![Bildschirmfoto zu 2021-01-15 20-06-22|417x500](upload://jE3ULqJcr7mK3bQ1DicfKwK72mp.png)
)
)
[body:protected] => Slim\Psr7\Stream Object
(
[stream:protected] => Resource id #8
[meta:protected] => Array
(
[wrapper_type] => PHP
[stream_type] => TEMP
[mode] => w+b
[unread_bytes] => 0
[seekable] => 1
[uri] => php://temp
)
[readable:protected] =>
[writable:protected] => 1
[seekable:protected] =>
[size:protected] =>
[isPipe:protected] =>
[finished:protected] =>
[cache:protected] =>
)
)
But imo too late, because response is just done and the Header response in postman does depict the wrong value for Access-Control-Allow-Credentials
i.e. (true instead of false)
So where should I put the middleware class that it works?
furtheron appreciating any hints