在 Laravel 4 API 中完全禁用 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16415369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:45:34  来源:igfitidea点击:

Fully disable cookies in Laravel 4 API

apisession-cookieslaravellaravel-4

提问by Iso

I am using Laravel to build a RESTful API. I use Basic HTTP Auth (Authenticate header), with this filter:

我正在使用 Laravel 构建一个 RESTful API。我使用基本 HTTP 身份验证 ( 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);
    }
});

It works, but Laravel then tries to set a cookie for the user (sending a Set-Cookieheader). I tried setting the session.driverconfiguration key to array, only to see it now sends a Set-Cookie: laravel_session=deletedthingy.

它有效,但 Laravel 然后尝试为用户设置 cookie(发送Set-Cookie标头)。我尝试将session.driver配置密钥设置为array,只是看到它现在发送了一个Set-Cookie: laravel_session=deleted东西。

How can i fully disable this Set-Cookieheader?

如何完全禁用此Set-Cookie标头?

Thank you.

谢谢你。

回答by sebt

For stateless APIs, no cookies and clean headers the following works:

对于无状态 API,没有 cookie 和干净的标头,以下工作:

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

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:

请注意,上面使用的是 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() seems like a good approach for a stateless REST API. Each client request is authenticated and no session cookies are used in this approach.

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

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.

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

回答by Paul Wenzel

To disable sessions for all routes in a Laravel 4 controller, set the session driver option in the class construct:

要禁用 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.";
    }

}

回答by Rameez Rami

you need to create your filter like follws in laravel 4, 4.2

您需要在 laravel 4、4.2 中创建类似以下内容的过滤器

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

In laravel 5, 5.1 set middleware handle()like follows

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

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

回答by matpop

Try this - dirty, but works for me.
The example is for a single route, can be modified to manage route prefix and so on.
First, create a directory inside app/configfor a specific environment, let's say stateless.
Then, place a session.phpfile inside app/config/stateless, with code like below:

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

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

Finally, modify the detectEnvironmentpart in bootstrap/start.php:

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

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

You may want to have a look here.

你可能想看看这里

回答by ipalaus

Remove 'Illuminate\Cookie\CookieServiceProvider',from your providersarray in app.php. It should do the trick :)

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

回答by AlphaZygma

I'm developing an API using laravel, so definitely I don't want to use the cookies. However, I do want to use the sessions mechanism for APIs that require authentication.

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

So, I'm using the sessions.driver = "file"

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

To be able to use the mechanism, but allow to override the cookie set, after much debugging, I found out that there is some hardwiring at the Middleware class, but through the magic of filters, you can disable the feature right before the cookie is set.

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

So, on filters.php, I created the following filter, and added as an afterfilter of my route group

所以,在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');
});

Note:the only case where this filter will not get called and thus producing the cookie, is if an exception occurs, in which case you may want to update the config on your error handler as well (default error handler if you haven't overwritten laravel's). To override, look at app/start/global.php

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

回答by undeadking

You should modify session.php:

你应该修改session.php

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