如何在 Laravel 项目中设置 X-Frame-Options?

10

我希望防止我的网站被点击劫持攻击。在哪个文件中以及在哪里设置X-Frame-Options以防止点击劫持攻击。


1
这是一个解决方案,展示了如何设置X-Frame-Options。https://gist.github.com/EduardoSP6/221c75332de2dbebebe98bf51f80ddb5 - Waqleh
2个回答

23

你有两种方式:

  • 在反向代理(如Nginx)中设置它
add_header X-Frame-Options "SAMEORIGIN";
  • 将 Laravel 中间件 Illuminate\Http\Middleware\FrameGuard 应用到需要保护的路由上。
<?php

namespace Illuminate\Http\Middleware;

use Closure;

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);

        $response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);

        return $response;
    }
}

嘿,我遇到了同样的问题。我尝试了这种方法(FrameGuard),但我仍然得到了“拒绝显示...在框架中,因为它将'X-Frame-Options'设置为'sameorigin'”的错误信息,是我漏掉了什么吗? - H Mihail
1
@HMihail,听起来你想做的是与OP尝试做的相反的事情。(允许来自不同域的iframe而不是防止除同一域之外的所有内容。) - J.D. Sandifer
这对 API 路由也适用吗?我有一个单页应用程序。 - mafortis
2
它对JSON路由无效,只对HTML路由有效,因此它对你唯一的HTML路由有用。 - Shizzen83

4

要解决所有路由上的问题:

app/http/Kernel.php中的protected $middleware中添加FrameGuard::class,

默认情况下,FrameGuard.php设置为"SAMEORIGIN",但您可以根据需要更改以下行的第二个参数为"DENY""ALLOW-FROM uri"

$response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接