How to prevent xss with CSP

Content Security Policy explained

Posted by Michael Sundstrøm on 2021-02-16

There are a lot of bad people out there, but there is a few things you can do to prevent your site or visitors from being exploitet.

One of these things is Content Security Policies (CSP)

Content Security Policies allows you to control how scripts and other resources are handled by the browser.

You are able to allow only script files loaded in script tags from you domain (Very strict) to allowing unsafe inline scripts inserted by a wysiwyg editor (very unsafe) and everything in between depending on your needs.

How to set it up

It is quite easy to setup in web.config for you webserver and insert a custom header names “Content-Security-Policy” as shown below.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Content-Security-Policy" value="default-src 'self';" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

You are able to add allowed domains as well (Here googletagmanager.com)

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Content-Security-Policy" value="default-src 'self' googletagmanager.com;" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

I have started a Github repo where I have created a few examples (More will come over time) for easy configuration.

I have only scratched the surface of this tool.

If you want to know more have a look at https://content-security-policy.com/