Skip to content

Commit

Permalink
Dynamic Access-Control-Expose-Headers Support
Browse files Browse the repository at this point in the history
- Update CorsService to merge existing exposed headers with configured
- Add deduplication for exposed headers

#29
  • Loading branch information
yinheli authored and Heli Yin committed Jan 2, 2025
1 parent 6d89006 commit a3b7e15
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/CorsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,17 @@ private function configureAllowCredentials(Response $response, Request $request)

private function configureExposedHeaders(Response $response, Request $request): void
{
$existingExposedHeaders = $response->headers->get('Access-Control-Expose-Headers');
$exposedHeaders = $existingExposedHeaders ? array_map('trim', explode(',', $existingExposedHeaders)) : [];

if ($this->exposedHeaders) {
$response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->exposedHeaders));
$exposedHeaders = array_merge($this->exposedHeaders, $exposedHeaders);
}

$uniqueExposedHeaders = array_unique(array_filter($exposedHeaders));

if (!empty($uniqueExposedHeaders)) {
$response->headers->set('Access-Control-Expose-Headers', implode(', ', $uniqueExposedHeaders));
}
}

Expand Down
37 changes: 37 additions & 0 deletions tests/CorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,43 @@ public function itDoesntSetAccessControlAllowOriginWithoutOrigin(): void
$this->assertFalse($response->headers->has('Access-Control-Allow-Origin'));
}

/**
* @test
*/
public function itConfiguresExposedHeadersWhenResponseHasNoExistingHeaders(): void
{
$app = $this->createStackedApp([], [
'Access-Control-Expose-Headers' => 'X-Custom-1, X-Custom-2',
]);
$request = $this->createValidActualRequest();

$response = $app->handle($request);

$this->assertTrue($response->headers->has('Access-Control-Expose-Headers'));
$this->assertEquals('X-Custom-1, X-Custom-2', $response->headers->get('Access-Control-Expose-Headers'));
}

/**
* @test
*/
public function itMergesExposedHeadersWhenResponseHasExistingHeaders(): void
{
$app = $this->createStackedApp(
[
'exposedHeaders' => ['X-Option-1', 'X-Option-2'],
],
[
'Access-Control-Expose-Headers' => 'X-Custom-1',
]
);
$request = $this->createValidActualRequest();

$result = $app->handle($request);

$this->assertTrue($result->headers->has('Access-Control-Expose-Headers'));
$this->assertEquals('X-Option-1, X-Option-2, X-Custom-1', $result->headers->get('Access-Control-Expose-Headers'));
}

private function createValidActualRequest(): Request
{
$request = new Request();
Expand Down

0 comments on commit a3b7e15

Please sign in to comment.