There are 3 main types of Cross-site Scripting (XSS) attacks
Sanitize the input provided by the user - Dom Purify gihtub
JS-injection
on the browser. The attacker can act as a userAlso, the browsers take measurements against xss attacks to protect the users. We could even prevent from executing any javascript on the browser. But, the web application could require some javascript to function. Then, we can specify specific javascript that could be executed on the browser. To achieve that, we can set http header.
Content-Security-Policy: script-src 'none'
Content-Security-Policy: script-src 'self' https://example.com
example.com
unsafe-inline
: executes inline script tag
unsafe-inline
<script>alert(1)</script>
wouldn't be executed on the browserscript-src 'sha256-abcdef123456
CSP
hash value<script integrity='sha256-abcdef'>
: it is optional to provide integrity/hash value in the script tagnonce-radomvalue
in CSP
header
secrets
libraryimport secrets
secrets.token_hex(40)
<script src="some-script.js" nonce="randomvalue">