确保Laravel网站不会被嵌入到其他站点中的方法

时间:2022-07-27
本文章向大家介绍确保Laravel网站不会被嵌入到其他站点中的方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

HTTP 响应头部中,有一个字段,叫做 X-Frame-Options,该字段可以用来指示是否允许自己的网站被嵌入到其他网站的 <iframe 或者 <object 标签中。该头部有三个值

  1. DENY – 始终不允许嵌入,即使是同一个域名
  2. SAMEORIGIN – 只能在相同域名中嵌入
  3. ALLOW-FROM uri – 设置允许的域

通常,可以在 HTTP 代理中进行配置,比如 nginx

add_header X-Frame-Options SAMEORIGIN;

Laravel 自带了用来「只允许同域名嵌入」的中间件,我们只需要在 /app/Http/Kernel.php 中添加即可

// /app/Http/Kernel.php
protected $middleware = [
  IlluminateHttpMiddlewareFrameGuard::class,
];

该中间件的实现如下

<?php

namespace IlluminateHttpMiddleware;

use Closure;

class FrameGuard
{
  /**
   * Handle the given request and get the response.
   *
   * @param IlluminateHttpRequest $request
   * @param Closure $next
   * @return SymfonyComponentHttpFoundationResponse
   */
  public function handle($request, Closure $next)
  {
    $response = $next($request);

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

    return $response;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助。