问题 防止Laravel中的路由会话(自定义按需会话处理)


我正在使用laravel和默认会话驱动程序设置为REDIS为我的Android应用程序构建API。

我在这里找到了一篇好文章 http://dor.ky/laravel-prevent-sessions-for-routes-via-a-filter/ 哪种服务的目的。

然而,当我点击url时它也会击中redis并生成空的键。现在我想避免在redis中创建空的会话密钥。理想情况下它不应该打到redis我该怎么做?

我们能否以某种方式自定义sessios,以便仅为特定路由生成会话(或禁用特定路由)?

我可以用具体的用例解释一下,请告诉我。


2515
2017-10-20 19:06


起源



答案:


使用Laravel 5中的中间件非常容易,我需要一个没有会话的API密钥请求我只是做了:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession as BaseStartSession;

class StartSession extends BaseStartSession
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(\Request::has('api_key'))
        {
            \Config::set('session.driver', 'array');
        }
        return parent::handle($request, $next);
    }
}

您还需要按如下方式扩展SessionServiceProvider:

<?php namespace App\Providers;

use Illuminate\Session\SessionServiceProvider as BaseSessionServiceProvider;

class SessionServiceProvider extends BaseSessionServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerSessionManager();

        $this->registerSessionDriver();

        $this->app->singleton('App\Http\Middleware\StartSession');
    }
}

并放在你的 config/app.php 下 providers

'App\Providers\SessionServiceProvider',

您还必须在内核文件中更改它: App/Http/Kernel.php, 在里面 $middlewareGroups 部分更改默认条目, \Illuminate\Session\Middleware\StartSession::class, 到你的新班级 \App\Http\Middleware\StartSession::class,


8
2018-03-25 09:12



加 \Config::set('cookie.driver', 'array'); 还可以阻止应用在响应中发送Cookie。 - Marco Florian
你是什​​么意思app.conf ?? - kyo
应该是config / app.php - LukePOLO


答案:


使用Laravel 5中的中间件非常容易,我需要一个没有会话的API密钥请求我只是做了:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession as BaseStartSession;

class StartSession extends BaseStartSession
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(\Request::has('api_key'))
        {
            \Config::set('session.driver', 'array');
        }
        return parent::handle($request, $next);
    }
}

您还需要按如下方式扩展SessionServiceProvider:

<?php namespace App\Providers;

use Illuminate\Session\SessionServiceProvider as BaseSessionServiceProvider;

class SessionServiceProvider extends BaseSessionServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerSessionManager();

        $this->registerSessionDriver();

        $this->app->singleton('App\Http\Middleware\StartSession');
    }
}

并放在你的 config/app.php 下 providers

'App\Providers\SessionServiceProvider',

您还必须在内核文件中更改它: App/Http/Kernel.php, 在里面 $middlewareGroups 部分更改默认条目, \Illuminate\Session\Middleware\StartSession::class, 到你的新班级 \App\Http\Middleware\StartSession::class,


8
2018-03-25 09:12



加 \Config::set('cookie.driver', 'array'); 还可以阻止应用在响应中发送Cookie。 - Marco Florian
你是什​​么意思app.conf ?? - kyo
应该是config / app.php - LukePOLO


实现这一目标的最简单方法是创建自己的AppStartSession中间件,使其成为Illuminate \ Session \ Middleware \ StartSession的子类,并替换kernel.php中使用的类。您需要在子类中覆盖的唯一方法是sessionConfigured(),您可以返回false以禁用会话,或者使用parent :: sessionConfigured()来允许它。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession;

class AppStartSession extends StartSession
{
    protected function sessionConfigured(){
        if(!\Request::has('api_key')){
            return false;
        }else{
            return parent::sessionConfigured();
        }
    }
}

kernel.php(有关更改的位置,请参阅***注释)

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

       // *** Replace start session class
       // \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\AppStartSession::class,

        // *** Also comment these ones that depend on there always being a session.
        //\Illuminate\View\Middleware\ShareErrorsFromSession::class,
        //\App\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

不要打架子,拥抱它!


2
2017-08-08 11:15



为什么这个没有得到任何关注是有点担心的,因为[这些] Laravel“开发人员”没有看到框架中的模块化潜力,而是选择编写hackish works。其余的答案都是完整的枷锁。 - snh


在Laravel 5中,只是不要使用 StartSessionShareErrorsFromSession,和 VerifyCsrfToken 中间件。

在我的应用程序中,我已经移动了这三个中间件 web 小组到新的 stateful 小组,然后我把这个包括在内 stateful 需要了解会话的路线上的小组(除了 web 在所有情况下,至少在我的应用程序中)。其他路线属于 web 要么 api 组。

现在当向不使用的路由发出请求时 stateful 中间件组会话cookie不会被发回。


2
2018-03-13 08:07





从Laravel 5.2开始,当引入中间件组时,您可以通过在“Web”中间件组(包括负责会话处理的StartSession中间件)之外定义某些路由来禁用某些路由的会话。与最新的5.2.x版本一样,整个默认routes.php文件都包含“web”中间件组,您需要对其进行一些修改 app/Providers/RouteServiceProvider.php 文件,如上所述 这里


1
2017-08-05 10:02





我一直在努力完成类似的功能。

我们的API是无状态的,除了1路 - 版本1购物车。

我最终设定了 'driver' 在app / config / session.php中这样...

'driver' => 'v1/cart' === Request::getDecodedPath() ? 'native' : 'array',

没什么了不起的。最初我们使用的是前置过滤器,但这种情况发生的时间不够早。

这似乎是一种简单的做事方式,但我可能会遗漏一些东西。

将交换机放在配置中对于其他开发人员来说似乎是一个容易的地方,可以看到驱动程序是什么,而将其置于服务提供商中是如此隐蔽,不知道安装了哪些服务提供商以及他们与之交互的内容,它将是更难调试。

无论如何。希望这有一些用处。

正如下面所指出的......如果动态,请不要缓存您的配置。

这导致它的用途有限。一旦我们不再需要支持v1 / cart,我们将丢弃此路由,然后返回静态配置。


1
2018-01-20 09:52



如果您缓存配置,这将失败,而不是一个想法的情况 - LukePOLO


似乎有一种方法可以使用会话拒绝回调来实现此目的。

相关来源......

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/Application.php#L655

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/Application.php#L660

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Session/Middleware.php#L60

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Session/Middleware.php#L97

我在网上找不到很多这方面的引用,但是通过源读取更多内容似乎如果会话拒绝回调返回一个真值,会话将被强制使用数组驱动程序来处理请求而不是配置的任何内容。您的回调也会获取当前请求,因此您可以根据请求参数执行某些逻辑。

我只在本地的Laravel 4.2安装上测试了这个,但它似乎工作。您只需要将一个函数绑定到session.reject。

首先,创建一个SessionRejectServiceProvider(或类似的东西)

<?php

use \Illuminate\Support\ServiceProvider;

class SessionRejectServiceProvider extends ServiceProvider {

    public function register()
    {
        $me = $this;
        $this->app->bind('session.reject', function($app)use($me){
            return function($request)use($me){
                return call_user_func_array(array($me, 'reject'), array($request));
            };
        });
    }

    // Put the guts of whatever you want to do in here, in this case I've
    // disabled sessions for every request that is an Ajax request, you
    // could do something else like check the path against a list and
    // selectively return true if there's a match.
    protected function reject($request)
    {
        return $request->ajax();
    }

}

然后将其添加到app / config / app.php中的提供程序中

<?php

return array(
   // ... other stuff
   'providers' => array(
       // ... existing stuff...
       'SessionRejectServiceProvider',
   ),
);

编辑/更多信息

最终结果是,对应用程序的每个请求都会调用reject()方法, 之前 会话开始了。如果reject()方法返回true,则会话将设置为数组驱动程序,基本上什么都不做。你可以在$ request参数中找到很多有用的信息来确定这个,这里是4.2中请求对象的API参考。

http://laravel.com/api/4.2/Illuminate/Http/Request.html


0
2017-10-20 19:59



我做过类似的事情 stackoverflow.com/a/29251516/1212047 - LukePOLO