在 Laravel 4 API 中完全禁用 cookie [英] Fully disable cookies in Laravel 4 API
问题描述
我正在使用 Laravel 构建一个 RESTful API.我使用基本 HTTP 身份验证(Authenticate header
),带有这个过滤器:
I am using Laravel to build a RESTful API. I use Basic HTTP Auth (Authenticate header
), with this filter:
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
东西.
It works, but Laravel then tries to set a cookie for the user (sending a Set-Cookie
header). I tried setting the session.driver
configuration key to array
, only to see it now sends a Set-Cookie: laravel_session=deleted
thingy.
如何完全禁用此 Set-Cookie
标头?
How can i fully disable this Set-Cookie
header?
谢谢.
推荐答案
对于无状态 API、无 cookie 和干净的标头,以下工作:
For stateless APIs, no cookies and clean headers the following works:
Route::filter('auth.basic', function()
{
Config::set('session.driver', 'array');
return Auth::onceBasic();
});
请注意,上面使用的是 Auth::onceBasic() ,出于某种原因,它仍然发送Set-Cookie"标头.根据文档 onceBasic auth 是无状态的;也许 cookie 是出于信息目的而发送的,是调试模式的副作用,或者它可能是一个错误.无论哪种方式 Config::set(...) 仍然需要.使用此过滤器快速卷曲路由将返回以下标题:
Note that the above is using Auth::onceBasic() which for some reason still sends the "Set-Cookie" header. According to the docs onceBasic auth is stateless; perhaps the cookie is sent for information purposes, is a side-effect of debug mode, or maybe it's a bug. Either way Config::set(...) is still required. A quick curl on routes with this filter return the following headers:
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.
Auth::onceBasic() seems like a good approach for a stateless REST API. Each client request is authenticated and no session cookies are used in this approach.
注意.上述过滤器未捕获的其他路由仍将设置 cookie(并发送Set-Cookie"标头).因此,此解决方案适用于无状态 API 和无状态 API 的常见情况.有状态的网络访问/管理员.
nb. Other routes not caught by the above filter and will still set cookies (and send the "Set-Cookie" header). So this solution works for the common situation of both stateless API & stateful web access/admin.
这篇关于在 Laravel 4 API 中完全禁用 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!