在Laravel中防止路由会话(自定义按需会话处理)
我正在使用laravel和默认会话驱动程序设置为REDIS来为我的Android应用程序构建API.
I am building APIs for my Android app using laravel and default session driver set to REDIS.
我在这里 http://dor.ky/laravel-通过某种过滤器/来防止路由的会话.
I found a good article here http://dor.ky/laravel-prevent-sessions-for-routes-via-a-filter/ which sort of serves the purpose.
但是,无论何时我击中url,它也会击中redis并生成为空的密钥.现在,我要避免在Redis中创建空的会话密钥.理想情况下,它不应该影响redis我该怎么办?
However when ever I hit the url it also hits the redis and generates the key which is empty. Now I want avoid creating empty session keys in redis. Ideally it should not hit the redis How can I do that?
我们可以通过某种方式自定义sessios,以便仅针对特定路由生成会话(或针对特定路由禁用会话)吗?
Can we customise sessios in a way so that sessions are generated only for specific routes (or disable for specific routes)?
我可以用具体的用例进行更多的解释,请告诉我.
I can explain more with specific use case, please let me know.
使用Laravel 5中的中间件真的很容易,我需要带有API密钥的任何请求都没有会话,而我只是这样做了:
Its really easy using the middleware in Laravel 5, I needed any request with an API key not to have a session and I simply did :
<?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,如下所示:
Also you will need to extend the SessionServiceProvider as follows:
<?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');
}
}
并放在providers
下的config/app.php
中:
'App\Providers\SessionServiceProvider',
还必须在内核文件中进行更改:App/Http/Kernel.php
,在$middlewareGroups
部分中,将默认条目\Illuminate\Session\Middleware\StartSession::class,
更改为新类\App\Http\Middleware\StartSession::class,
.
Also you must change it in your kernel file: App/Http/Kernel.php
, in the $middlewareGroups
section change the default entry, \Illuminate\Session\Middleware\StartSession::class,
to your new class \App\Http\Middleware\StartSession::class,
.