Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active April 5, 2024 20:37
Show Gist options
  • Save EduardoSP6/221c75332de2dbebebe98bf51f80ddb5 to your computer and use it in GitHub Desktop.
Save EduardoSP6/221c75332de2dbebebe98bf51f80ddb5 to your computer and use it in GitHub Desktop.
How to set X-Frame-Options headers in Laravel
1- Create a Middleware:
$ php artisan make:middleware XFrameHeadersMiddleware
Content:
<?php
namespace App\Http\Middleware;
use Closure;
class XFrameHeadersMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
/**
* This middleware was created to prevent OWASP warnings, like:
*
* The X-Frame-Options header is not set in the HTTP response, meaning the page can potentially be loaded into
* an attacker-controlled frame. This could lead to clickjacking, where an attacker adds an invisible layer on
* top of the legitimate page to trick users into clicking on a malicious link or taking a harmful action.
*
* The X-Frame-Options allows three values: DENY, SAMEORIGIN and ALLOW-FROM. It is recommended to use DENY,
* which prevents all domains from framing the page or SAMEORIGIN, which allows framing only by the same site.
* DENY and SAMEORGIN are supported by all browsers. Using ALLOW-FROM is not recommended because not all browsers support it.
*
* For more information, access: https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html
*
*/
$response = $next($request);
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
return $response;
}
}
2- Add this to one of the middleware arrays in Kernel.php:
protected $middleware = [
\App\Http\Middleware\XFrameHeadersMiddleware::class,
];
@calebadeleye
Copy link

thansk

@renaldiadrian98
Copy link

Thanks

@mateusgalasso
Copy link

thanks

@riobayusentosa
Copy link

Did someone tried this? @calebadeleye @renaldiadrian98 @stonkeep

this is not working ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment