Member-only story
API Extra Security Layer with XSS Protection using Laravel
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!
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=' javascript:alert(1)'>CLICK</a>");
The output is just<a > Click</a>
🤘