Member-only story

API Extra Security Layer with XSS Protection using Laravel

Hafiq Iqmal
2 min readJan 25, 2021

--

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> 🤘

--

--

Hafiq Iqmal
Hafiq Iqmal

Written by Hafiq Iqmal

Technical Lead | Software Engineer | Laravel Enthusiasts | Tech writer | UiTM Alumni | Husband | Proud father of a beautiful daughter

No responses yet