防範網頁被內嵌成 iframe

由於資安越來越嚴謹,現在很多網站都會阻擋被其他網頁用 iframe 內嵌。

常見的作法是在回應標頭加上 X-Frame-Options,這時開啟「開發人員工具」會看到↓
還有另外一個作法是設定 Content-Security-Policy,「開發人員工具」看到的訊息是↓

Laravel8.x 統一在每個 request 加上 X-Frame-Options: SAMEORIGIN。但有些時候我們是希望網頁可以被內嵌的,例如讓 APP 透過 WebView 看網頁,這時就必須關閉這項設定。

1. 建立新的 FrameGuard Middleware,複製 \Illuminate\Http\Middleware\FrameGuard,並加上需要的判斷
<?php

namespace App\Http\Middleware;

use Closure;
use Route;

class FrameGuard
{
    /**
     * Handle the given request and get the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (Route::currentRouteName() != '{your.route.name}') {
            $response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);
        }

        return $response;
    }
}
2. 開啟 app\Http\Kernel.php,替換 FrameGuard
class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
       ...
        // \Illuminate\Http\Middleware\FrameGuard::class,
        \App\Http\Middleware\FrameGuard::class,
    ];
    ...

留言