在我的laravel应用中,我想先验证客户端是否具有cookie,然后再将其重定向到实际文件。为此,我创建了一个控制器函数来接收我创建的新路由:
Route::group(['middleware'=>['web']], function(){
Route::get('/storage/{filename}', 'HomeController@getArquivo');
}
控制器:
class HomeController extends Controller{
public function getArquivo($filename)
{
if(hasCookie()) Redirect::to('/storage/' . $filename);
else Redirect::to('/some/other/address');
}
}
例如,在我的存储中,我有一个名为8-0.jpeg
的文件,并且仅当我传递与其不同的文件名时才调用getArquivo
函数(例如url.com/storage/something) 。如果我传递的是确切的文件名url.com/storage/8-0.jpeg),那么它只会返回忽略路线的图片。所以我的问题是,如何强制GET请求始终先通过此控制器?预先感谢。
编辑:我已根据提供的答案进行了更改,但无法正常使用。现在的代码如何:
中间件:
class VerificaCookieArquivo
{
var $nomeBiscoitoSessao = "biscoito";
public function handle($request, Closure $next)
{
if ($this->temBiscoito()) {
return $next($request);
}
return Redirect::to('/some/other/address');
}
private function temBiscoito(){
return isset($_COOKIE[$this->nomeBiscoitoSessao]);
}
}
Kernel.php
:
protected $routeMiddleware = [
//other middlewares
'verificaCookieArquivo' => \Ibbr\Http\Middleware\VerificaCookieArquivo::class,
];
在路由(web.php
)中,我为此cookie检查创建了一个单独的路由组,因为我不希望它影响我拥有的其他路由:
Route::group(['middleware'=>['verificaCookieArquivo']], function()
{
Route::get('/storage/{filename}', 'HomeController@getArquivo');
});
在HomeController.php中:
public function getArquivo($filename){
$fullpath = "/storage/" . $filename;
return response()->download(storage_path($fullpath), null, [], null);
}
仍然无法正常工作,其行为仍然与以前相同
答案 0 :(得分:1)
创建一个中间件,该中间件将使用有效的Cookie检查访问者。您可以这样创建它
中间件类
namespace App\Http\Middleware;
use Closure;
class SecureFile
{
public function handle($request, Closure $next)
{
if ($this->hasCookie()) {
return $next($request);
}
return redirect('/some/other/address');
}
private function hasCookie(){
//check cookie here and return ture or false
return true;
}
}
现在将此SecureFile
中间件添加到Kernel.php中的routeMiddleware
protected $routeMiddleware = [
...
...
'secureFile' => \App\Http\Middleware\SecureFile::class,
];
最后一步,请使用此中间件来路由
Route::group(['middleware'=>['web','secureFile']], function(){
Route::get('/storage/{filename}', 'HomeController@getArquivo');
}
在控制器中
class HomeController extends Controller{
public function getArquivo($filename)
{
$fullpath = "any_sub_folder/" . $filename;
return response()->download(storage_path($fullpath), null, [], null);
//https://laravel.com/docs/5.6/responses#file-downloads
}
}
编辑
看来您在public/storage
文件夹中有图像,那么图像将直接加载,不会调用您的路线。尝试将图像放置在storage
文件夹中,并添加其他路由
Route::get('file/{filename}', 'HomeController@getArquivo')->middleware('secureFile');
答案 1 :(得分:0)
使用以下方法在LAravel中创建中间件:
php artisan make:middleware CookieCheck
将此中间件添加到Kernel.php
文件中
将这些中间件添加到路由:
Route::group(['middleware'=>['web','cookie:check']], function(){
Route::get('/storage/{filename}', 'HomeController@getArquivo');
}
将Cookie校验代码放入中间件。