是否可以在用户允许之前阻止 Laravel 设置任何形式的 cookie?我在 github 上找到了一些 cookie-consent-packages,但它们都没有阻止 Laravel 设置初始 session-cookie 或 xsrf-cookie。
我可以使用某种中间件/配置拦截会话/xsrf-cookies,并根据是否找到同意cookie来阻止/允许它吗?
我已经解决了,但不确定这是否是正确的方法。我就是这样做的:
class CustomStartSession extends StartSession
{
protected function handleStatefulRequest(Request $request, $session, Closure $next)
{
// check if consent-cookie is set
$consent = $request->cookies->has('consent');
$request->setLaravelSession(
$this->startSession($request, $session)
);
$this->collectGarbage($session);
$response = $next($request);
$this->storeCurrentUrl($request, $session);
// if consent-cookie is set, add the cookie
if ($consent) {
$this->addCookieToResponse($response, $session);
}
$this->saveSession($request);
return $response;
}
}
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// replace StartSession with CustomStartSession
$middleware->web(replace: [StartSession::class => CustomStartSession::class]);
// remove ValidateCsrfToken-middleware
$middleware->web(remove: [ValidateCsrfToken::class]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
可能也应该子类化 ValidateCsrfToken 并检查那里的同意 cookie。现在我决定完全删除它,因为我的项目中没有任何“重要”表单。