阻止 Laravel 11 设置任何 cookie(包括 session/xsrf-cookies)?

问题描述 投票:0回答:1

是否可以在用户允许之前阻止 Laravel 设置任何形式的 cookie?我在 github 上找到了一些 cookie-consent-packages,但它们都没有阻止 Laravel 设置初始 session-cookie 或 xsrf-cookie。

我可以使用某种中间件/配置拦截会话/xsrf-cookies,并根据是否找到同意cookie来阻止/允许它吗?

cookies laravel-11
1个回答
0
投票

我已经解决了,但不确定这是否是正确的方法。我就是这样做的:

  1. 创建一个名为 CustomStartSession 的新中间件,扩展 StartSession 并覆盖 handleStatefulRequest() 方法:
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;
    }
}
  1. 然后在 bootstrap/app.php 中,将 StartSession 替换为 CustomStartSession,并删除 ValidateCsrfToken:
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。现在我决定完全删除它,因为我的项目中没有任何“重要”表单。

© www.soinside.com 2019 - 2024. All rights reserved.