Skip to content

Commit dc0f317

Browse files
committed
Refactor CORS configuration to ensure allowed origins are fully qualified URLs for better compatibility
1 parent d7613fa commit dc0f317

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

backend/config/cors.php

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,40 @@
1919

2020
'allowed_methods' => ['*'],
2121

22-
'allowed_origins' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
23-
'%s%s',
24-
'localhost,localhost:3000,localhost:3001,127.0.0.1,127.0.0.1:8000,::1',
25-
Laravel\Sanctum\Sanctum::currentApplicationUrlWithPort()
26-
))),
22+
/*
23+
|--------------------------------------------------------------------------
24+
| Allowed Origins
25+
|--------------------------------------------------------------------------
26+
|
27+
| Sanctum stores stateful domains as host names (without a scheme), but the
28+
| CORS layer expects fully qualified origins. Converting the configured
29+
| domains to http/https origins keeps credentialed requests working in
30+
| local development while still allowing overrides through the env file.
31+
|
32+
*/
33+
'allowed_origins' => array_map(
34+
static function (string $domain): string {
35+
$trimmed = trim($domain);
36+
if ($trimmed === '') {
37+
return $trimmed;
38+
}
39+
40+
if (str_contains($trimmed, '://')) {
41+
return $trimmed;
42+
}
43+
44+
if ($trimmed === '::1') {
45+
return 'http://[::1]';
46+
}
47+
48+
return sprintf('http://%s', $trimmed);
49+
},
50+
array_filter(explode(',', env('CORS_ALLOWED_ORIGINS', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
51+
'%s,%s',
52+
'localhost,localhost:3000,localhost:3001,127.0.0.1,127.0.0.1:3000,127.0.0.1:8000,::1',
53+
Laravel\Sanctum\Sanctum::currentApplicationUrlWithPort()
54+
)))))
55+
),
2756

2857
'allowed_origins_patterns' => [],
2958

@@ -35,4 +64,4 @@
3564

3665
'supports_credentials' => true,
3766

38-
];
67+
];

0 commit comments

Comments
 (0)