8

I want to prevent my website from clickJacking attack. In which file and where to set X-Frame-Options for preventing clickJacking attack.

Darshan Prajapati
  • 914
  • 3
  • 8
  • 19
  • 1
    here is a solution that shows how to set `X-Frame-Options` https://gist.github.com/EduardoSP6/221c75332de2dbebebe98bf51f80ddb5 – Waqleh Oct 06 '21 at 12:24

2 Answers2

22

You have 2 ways:

  • Setup it in a reverse proxy such as Nginx
add_header X-Frame-Options "SAMEORIGIN";
  • Use Laravel middleware Illuminate\Http\Middleware\FrameGuard onto the routes you want to protect.
<?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;
    }
}
Shizzen83
  • 3,325
  • 3
  • 12
  • 32
  • Hey, I got the same problem. I tried this approach (FrameGuard), but I still get `Refused to display ... in a frame because it set 'X-Frame-Options' to 'sameorigin'`, Missing something? – H Mihail Sep 22 '20 at 05:51
  • 1
    @HMihail It sounds like you want to do the opposite of what the OP is trying to do. (Allow an iframe from a different domain instead of preventing it from all but the same domain.) – J.D. Sandifer Dec 04 '20 at 17:23
  • does this works for api routes as well? I have SPA app. – mafortis Dec 22 '20 at 03:00
  • 2
    It is useless against JSON routes, only HTML ones, so it would be useful against your only HTML route – Shizzen83 Dec 22 '20 at 18:34
2

To fix the problem on all your routes :

Add FrameGuard::class, on the protected $middleware in your app/http/Kernel.php

FrameGuard.php by default is set to "SAMEORIGIN", but you can change the second parameter of the following line with "DENY" or "ALLOW-FROM uri" (according to your needs) :

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

cbenoit
  • 21
  • 3