我想在应用程序上的所有响应中添加http响应标头。我刚刚创建了一个新的中间件,以便执行以下操作:
namespace Ibbr\Http\Middleware;
use Closure;
class XFrameOptionsHeader
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('X-Frame-Options', 'deny');
return $response;
}
}
然后,将其添加到我的Kernel.php
protected $middlewareGroups = [
'web' => [
\Ibbr\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Ibbr\Http\Middleware\VerifyCsrfToken::class,
\Ibbr\Http\Middleware\XFrameOptionsHeader::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \Ibbr\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verificaCookieArquivo' => \Ibbr\Http\Middleware\VerificaCookieArquivo::class,
'xFrameOptionsHeader' => \Ibbr\Http\Middleware\XFrameOptionsHeader::class,
]
在路线定义中,我有:
Route::group(['middleware'=>['verificaCookieArquivo']], function(){
Route::get('/storage/{filename}', 'PagesController@getArquivo');
});
Route::group(['middleware'=>['web','xFrameOptionsHeader']], function(){
Route::get('/', 'PagesController@getIndex');
// more routes...
});
每当我呼叫第二组['web','xFrameOptionsHeader']
中的任何路由时,它会正常工作并返回新的http标头。但是,当我调用路由/storage/{filename}
时,它失败并显示错误
调用未定义的方法 Symfony \ Component \ HttpFoundation \ BinaryFileResponse :: header()
因此,在考虑这种情况下是否存在头函数之前,我首先感到奇怪的是,甚至在这种情况下都调用了这种中间件,在这种情况下,我认为它只会调用verificaCookieArquivo
。为什么会发生这种情况以及如何解决?顺便说一句,我正在使用laravel-5.7,但是这里没有标签。
答案 0 :(得分:0)
只需从\Ibbr\Http\Middleware\XFrameOptionsHeader::class,
中间件组中删除web
。
web
中间件组将自动应用于routes/web.php
。因此,这就是运行中间件的原因:
Route::group(['middleware'=>['verificaCookieArquivo']], function(){
Route::get('/storage/{filename}', 'PagesController@getArquivo');
});
此外,您也无需在下一个路由组中指定web
:
Route::group(['middleware'=>['web','xFrameOptionsHeader']], function(){
// ^-- Remove this
Route::get('/', 'PagesController@getIndex');
// more routes...
});
参考:https://laravel.com/docs/5.6/middleware#middleware-groups