【问题标题】:Fully disable cookies in Laravel 4 API在 Laravel 4 API 中完全禁用 cookie
【发布时间】:2022-01-30 22:21:02
【问题描述】:

我正在使用 Laravel 构建一个 RESTful API。我使用 Basic HTTP Auth (Authenticate header) 和这个过滤器:

Route::filter('auth', function()
{
    $credentials = ['email' => Request::getUser(), 'password' => Request::getPassword()];

    if (!Auth::once($credentials)) {
        $response   = ['error' => true, 'message' => 'Unauthorized request'];
        $code       = 401;
        $headers    = ['WWW-Authenticate' => 'Basic'];

        return Response::json($response, $code, $headers);
    }
});

它可以工作,但是 Laravel 会尝试为用户设置一个 cookie(发送一个 Set-Cookie 标头)。我尝试将session.driver 配置键设置为array,却发现它现在发送了Set-Cookie: laravel_session=deleted 的东西。

我怎样才能完全禁用这个Set-Cookie 标头?

谢谢。

【问题讨论】:

  • 你试过 Laravel 4 原生的基本认证过滤器auth.basic吗?
  • @Usman 是的,它的工作原理几乎相同,只是它发送了一个 WWW-Authenticate 响应标头,这是我不想要的。它还设置了laravel_session cookie。
  • 供将来参考 - 在 Laravel 5 中,只需使用数组进行会话存储并在 config/app.php 中禁用 cookie 支持。不要忘记使用 artisan 来清除编译。

标签: api session-cookies laravel laravel-4


【解决方案1】:

对于无状态 API,没有 cookie 和干净的标头可以使用以下方法:

Route::filter('auth.basic', function()
{
    Config::set('session.driver', 'array');
    return Auth::onceBasic();
});

请注意,上面使用的是 Auth::onceBasic() ,由于某种原因仍然发送“Set-Cookie”标头。根据文档,onceBasic auth 是无状态的;也许cookie是为了提供信息而发送的,是调试模式的副作用,或者是一个错误。无论哪种方式 Config::set(...) 仍然是必需的。使用此过滤器快速卷曲路由会返回以下标头:

HTTP/1.1 200 OK
Date: Wed, 12 Feb 2014 02:34:26 GMT
Server: Apache/2.4.6 (Ubuntu)
X-Powered-By: PHP/5.5.3
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Content-Type: application/json

Auth::onceBasic() 似乎是无状态 REST API 的好方法。每个客户端请求都经过身份验证,并且在此方法中不使用会话 cookie。

注意。上述过滤器未捕获的其他路由仍将设置 cookie(并发送“Set-Cookie”标头)。因此,此解决方案适用于无状态 API 和有状态 Web 访问/管理的常见情况。

【讨论】:

    【解决方案2】:

    要禁用 Laravel 4 控制器中所有路由的会话,请在类构造中设置会话驱动程序选项:

    <?php
    
    class ExampleController extends BaseController {
    
        public function __construct()
        {
            Config::set('session.driver', 'array');
        }
    
        public function getExample()
        {
            return "This example response should have no session cookie.";
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      你需要像在 laravel 4、4.2 中一样创建你的过滤器

      Route::filter('no.session.cookie', function()
      {
          Config::set('session.driver', 'array');
          Config::set('cookie.driver', 'array');
      });
      

      在 laravel 5、5.1 中设置中间件handle() 如下

      public function handle($request, Closure $next){
        \Config::set('session.driver', 'array');
        \Config::set('cookie.driver', 'array');
       return $next($request);
      }
      

      【讨论】:

        【解决方案4】:

        试试这个 - 很脏,但对我有用。
        以单条路由为例,可修改为管理路由前缀等。
        首先,在app/config 中为特定环境创建一个目录,比如stateless
        然后,在app/config/stateless 中放置一个session.php 文件,代码如下:

        <?php
        return array(
            'driver' => 'array'
        );
        

        最后修改bootstrap/start.php中的detectEnvironment部分:

        $env = $app->detectEnvironment(function()
        {
            if ($_SERVER['REQUEST_URI'] == '/your/route') return 'stateless';
        });
        

        【讨论】:

          【解决方案5】:

          app.php 中的 providers 数组中删除 'Illuminate\Cookie\CookieServiceProvider',。它应该可以解决问题:)

          【讨论】:

          • 不,现在我有一个 ReflectionException:“类 cookie 不存在”(在 bootstrap/compiled.php 中)。看起来它源于vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php:20:$guard-&gt;setCookieJar($this-&gt;app['cookie']);。感谢您的帮助!
          • Mmmm...如果您删除 Session 提供程序会发生什么?我在过去的某个时候做过这个把戏,但我不记得在哪里! :(
          • 同样的事情发生了,但在“课堂会话”中。您确定要删除提供商吗?
          • 当编译文件中的某些内容似乎产生错误时,最好清除该文件,例如使用artisan clear:compiled
          【解决方案6】:

          我正在使用 laravel 开发一个 API,所以我绝对不想使用 cookie。 但是,我确实想对需要身份验证的 API 使用会话机制。

          所以,我正在使用sessions.driver = "file"

          为了能够使用该机制,但允许覆盖cookie集,经过多次调试,我发现中间件类有一些硬接线,但是通过过滤器的魔力,您可以在之前禁用该功能cookie 已设置。

          所以,在filters.php,我创建了以下过滤器,并添加为我的路由组的after 过滤器

          /*
          |--------------------------------------------------------------------------
          | Custom Filter to remove the session cookie
          |--------------------------------------------------------------------------
          |
          | By default, if session driver is other than `null` or `array`, it will
          | create a cookie and pass the encrypted session id so that it can be used
          | across web requests.
          | However, since our application is an API, we dont need the cookie, but
          | we still want to be able to use the session functionality, so to allow
          | this, we just need to set the driver to `array` right before the 
          | dispatcher gets to the point to add the session cookie.
          | 
          | This is the Laravel call stack
          | \Illuminate\Session\Middleware::handle()
          |   -> \Illuminate\Session\Middleware::addCookieToResponse()
          |        -> \Illuminate\Session\Middleware::sessionIsPersistent()
          |
          | All session handling and file storage has happened before sessionIsPersistent()
          | is called, so we are safe to add an `after` filter that will reset
          | the driver in the configuration and thus preventing this specific
          | cookie to be added, all other previously added cookies will be 
          | kept (if any added) and thus sent as part of the response.
          */
          Route::filter('session.cookie.remove', function(){
              // Has to be 'array' because null, will prevent from writing sessions
              Config::set('session.driver', 'array');
          });
          

          注意:唯一不会调用此过滤器并因此生成 cookie 的情况是,如果发生异常,在这种情况下,您可能还需要更新错误处理程序上的配置(如果你没有覆盖 laravel 的默认错误处理程序)。 要覆盖,请查看app/start/global.php

          【讨论】:

            【解决方案7】:

            你应该修改session.php:

            <?php
            return array(
                'driver' => isset($_SERVER['REQUEST_URI']) && (stripos($_SERVER['REQUEST_URI'], '/api') === 0) ? 'array' : 'native'
            );
            

            【讨论】:

              猜你喜欢
              • 2011-09-23
              • 2013-09-11
              • 1970-01-01
              • 2017-12-02
              • 1970-01-01
              • 1970-01-01
              • 2015-08-24
              • 2015-05-15
              相关资源
              最近更新 更多