Phred/src/Http/Middleware/Security/SecureHeadersMiddleware.php

39 lines
1.3 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Phred\Http\Middleware\Security;
use Phred\Http\Middleware\Middleware;
use Phred\Support\Contracts\ConfigInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Middleware to add common security headers to the response.
*/
final class SecureHeadersMiddleware extends Middleware
{
public function __construct(
private readonly ConfigInterface $config
) {}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
2025-12-22 22:04:15 +00:00
$response = $this->profile($request, $handler);
// Standard security headers
$response = $response->withHeader('X-Content-Type-Options', 'nosniff')
->withHeader('X-Frame-Options', 'SAMEORIGIN')
->withHeader('X-XSS-Protection', '1; mode=block')
->withHeader('Referrer-Policy', 'no-referrer-when-downgrade')
->withHeader('Content-Security-Policy', $this->config->get('security.csp', "default-src 'self'"));
if ($this->config->get('security.hsts', true)) {
$response = $response->withHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
return $response;
}
}