Skip to content
All posts
LaravelAPISecurity

API extra security layer with XSS Protection using Laravel

January 25, 2021·Read on Medium·

Cross-site scripts (XSS) attack is where the attacker execute malicious scripts in a web browser of the victim by including malicious code in a legitimate web page or web application. An application is vulnerable to XSS if the application not sanitize user input and output.

So, basically, don’t trust user input!

freepik.com

In Laravel, we can avoid XSS Attack by using Middleware.

We can start by using existing AntiXSS package

composer require voku/anti-xss

After that,

Create a Middleware let’s say PurifyIncomingRequest.php

class PurifyIncomingRequest extends TransformsRequest {
...
}

Add transform function

protected function transform($key, $value)
{
return (new AntiXSS())->xss_clean(trim($value))
}

Whats it do? Every input from client is checked by AntiXSS function. If there is any xss input, it will be sanitize

For example

$harmless_string = (new AntiXSS())->xss_clean("<a href='&#x2000;javascript:alert(1)'>CLICK</a>");

The output is just<a > Click</a> 🤘

So, the final code would be like below

<?php

namespace
App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TransformsRequest;

class PurifyIncomingRequest extends TransformsRequest
{
protected $except = [
'password',
'password_confirmation',
];

protected function transform($key, $value)
{
if (in_array($key, $this->except, true)) {
return $value;
}

return $this->stripXSS($value);
}

private function stripXSS($value)
{
return is_string($value) ? strip_tags(antixss()->xss_clean(trim($value))) : $value;
}
}

Above code, i added some exclusion for password input. I want to avoid password input to be replace with other characters.

You can try on your own based on your implementation.

By the way… This is important…

Done rely on your code. You need to configure your web server configuration to add X-XSS-Protection in every http header. It will help you to defend against Cross-Site Scripting attacks. XSS Filter is only enabled by default in modern web browser such as, Chrome, IE, and Safari. This header stops pages from loading when they detect reflected XSS attacks.

Apache HTTP Server

Add the following entry in httpd.conf of your Apache webserver and restart the apache to verify

Header set X-XSS-Protection "1; mode=block"

Nginx

Add the following in nginx.conf under http block and restart your nginx

add_header X-XSS-Protection "1; mode=block";

That’s it. A simple validation in Laravel. Hope its help 😁

Thanks for your time.

Found this helpful?

If this article saved you time or solved a problem, consider supporting — it helps keep the writing going.

Originally published on Medium.

View on Medium
API extra security layer with XSS Protection using Laravel — Hafiq Iqmal — Hafiq Iqmal