I'm encountering a CORS issue with my Laravel application. I have a custom CORS middleware (OwnCors) that I'm using to handle CORS requests. Despite configuring it to allow credentials, I'm facing an issue where the Access-Control-Allow-Credentials header is not set correctly.
Here's my OwnCors middleware class:
class OwnCors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
if ($request->getMethod() == "OPTIONS") {
return response('OK')
->withHeaders($headers);
}
$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
And here's my CORS configuration (config/cors.php):
<?php
return [
'paths' => ['api/*', 'api/admin/*','*'],
'allowed_methods' => ['POST', 'GET', 'DELETE', 'PUT', '*'],
'allowed_origins' => ['http://localhost:3000','https://personaltrainerkmm.com','https://traning-app.vercel.app','*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
Despite setting 'supports_credentials' => true, the Access-Control-Allow-Credentials header in the response is not being set correctly. Instead, it's empty.
I'm making requests from a frontend hosted on https://fitnesspt.personaltrainerkmm.com to a backend hosted on https://personaltrainerkmm.com.
How can I ensure that Laravel properly sets the Access-Control-Allow-Credentials header to true in the response to resolve this CORS issue?
Any help or insights would be greatly appreciated. Thank you!
OwnCorsand solely rely on the config inconfig/cors.phpinstead. Also, note that, if your frontend has originhttps://fitnesspt.personaltrainerkmm.com, you'll need to list that as an allowed origin;https://personaltrainerkmm.comwon't do.