首页 > 解决方案 > 设置 cookie 时 Laravel CORS 不起作用

问题描述

\Fruitcake\Cors\HandleCors在 Laravel 应用程序中使用 CORS 中间件。

我的cors.php文件如下所示:

   '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,

我正在设置cookie作为响应:

$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);

最后,我从正在运行的 React 应用程序调用这个 api 端点https://localhost:3000

它给了我一个错误,说不允许 CORS(经典 CORS 错误)。

但是当我从响应中删除 cookie 时,它​​工作正常。

我还需要什么其他设置才能让它工作?

标签: phplaravelcorslaravel-8

解决方案


不确定这是否是您要寻找的,但我使用的是 laravel 5.3,并且必须为从另一个应用程序对我的应用程序进行的 API 调用添加 CORS 支持,这就是我所做的。

在 app\Http\Middlewear 中,我创建了一个名为 Cors.php 的文件并将其放置在以下位置:

<?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;
}

}

然后在我添加的受保护的 $routeMiddleware 内的 App\Http\Kernel.php

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

然后在我的路线中,无论需要什么CORS,我都添加了中间件

    Route::post('/my/api/call', 'MyController@MyApiRoute')->middleware(['cors']);

推荐阅读