-1

I am using \Fruitcake\Cors\HandleCors middleware for CORS in a Laravel app.

My cors.php file looks like this:

   'paths' => ['api/*', 'oauth/*', '*'],

    'allowed_methods' => ['POST', 'GET', 'DELETE', 'PUT', '*'],

    'allowed_origins' => ['http://localhost:3000', 'https://localhost:3000'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

I am setting cookie in response like this:

$access_cookie = Cookie::make('access_token', $access_token, $cookieLife, null, null, true);
$refresh_cookie = Cookie::make('refresh_token', $refresh_token, $MINUTES_IN_ONE_YEAR, null, null, true);
    
    
     return response()
                ->json(['tokens' => ['access_token' => $access_token, 'refresh_token' => $refresh_token], 'user' => $user])->withCookie($access_cookie)->withCookie($refresh_cookie);

Finally, I am calling this api endpoint from React app which is running on https://localhost:3000

It gives me an error saying that CORS not allowed ( Classic CORS error ).

But when I remove the cookie from the response, then It works fine.

What other setting do I need to get it to work?

Rakesh K
  • 1,290
  • 1
  • 16
  • 43

1 Answers1

-1

Not sure if this is what your looking for but im using laravel 5.3 and had to add CORS support for a API call that was made to my application from a different application and this is what i did.

in app\Http\Middlewear i created a file called Cors.php and placed teh following:

<?php namespace App\Http\Middleware;

use Closure;

 class Cors {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

}

Then in App\Http\Kernel.php inside the protected $routeMiddleware i added

   'cors' => \App\Http\Middleware\Cors::class,

and then in my routes whatever requires CORS i added the the middlewear

    Route::post('/my/api/call', 'MyController@MyApiRoute')->middleware(['cors']);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Yeak
  • 2,470
  • 9
  • 45
  • 71