mirror of
https://github.com/shlinkio/shlink.git
synced 2026-03-06 23:33:13 +08:00
Make sure Access-Control-Allow-Credentials is always set if configured
This commit is contained in:
@@ -37,7 +37,19 @@ final readonly class CorsOptions
|
||||
);
|
||||
}
|
||||
|
||||
public function responseWithAllowOrigin(RequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
/**
|
||||
* Creates a new response which contains the CORS headers that apply to provided request
|
||||
*/
|
||||
public function responseWithCorsHeaders(RequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
$response = $this->responseWithAllowOrigin($request, $response);
|
||||
return $this->allowCredentials ? $response->withHeader('Access-Control-Allow-Credentials', 'true') : $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* If applicable, a new response with the appropriate Access-Control-Allow-Origin header is returned
|
||||
*/
|
||||
private function responseWithAllowOrigin(RequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
if ($this->allowOrigins === '*') {
|
||||
return $response->withHeader('Access-Control-Allow-Origin', '*');
|
||||
|
||||
@@ -9,6 +9,7 @@ use Laminas\Diactoros\ServerRequestFactory;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\Attributes\TestWith;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Shlinkio\Shlink\Core\Config\Options\CorsOptions;
|
||||
|
||||
class CorsOptionsTest extends TestCase
|
||||
@@ -28,10 +29,30 @@ class CorsOptionsTest extends TestCase
|
||||
self::assertEquals($expectedAllowOrigins, $options->allowOrigins);
|
||||
self::assertEquals(
|
||||
$expectedAllowOriginsHeader,
|
||||
$options->responseWithAllowOrigin(
|
||||
ServerRequestFactory::fromGlobals()->withHeader('Origin', 'https://example.com'),
|
||||
new Response(),
|
||||
)->getHeaderLine('Access-Control-Allow-Origin'),
|
||||
$this->responseFromOptions($options)->getHeaderLine('Access-Control-Allow-Origin'),
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
#[TestWith([true])]
|
||||
#[TestWith([false])]
|
||||
public function expectedAccessControlAllowCredentialsIsSet(bool $allowCredentials): void
|
||||
{
|
||||
$options = new CorsOptions(allowCredentials: $allowCredentials);
|
||||
$resp = $this->responseFromOptions($options);
|
||||
|
||||
if ($allowCredentials) {
|
||||
self::assertEquals('true', $resp->getHeaderLine('Access-Control-Allow-Credentials'));
|
||||
} else {
|
||||
self::assertFalse($resp->hasHeader('Access-Control-Allow-Credentials'));
|
||||
}
|
||||
}
|
||||
|
||||
private function responseFromOptions(CorsOptions $options): ResponseInterface
|
||||
{
|
||||
return $options->responseWithCorsHeaders(
|
||||
ServerRequestFactory::fromGlobals()->withHeader('Origin', 'https://example.com'),
|
||||
new Response(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user