我正在使用 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