Man writting in desktop
Man writting in desktop

Understanding Content Security Policy (CSP) Basics

Hi welcome to another mini-post, this is about CSP let’s start defining CSP content security policy this is a security layer based on mitigation of XSS attacks and data injection.

To activate CSP you must make a setup in your server configuration to add this header Content-Security-Policy in some older versions, this header was X-Content-Security-Policy X-WebKit-CSP

or alternatively, you can set a meta tag defining it as this but not recommended:

<meta
  http-equiv="Content-Security-Policy"
  content=""
/>

What can we delimit with a CSP?

We can set policies based on this directives:

The values that we can set for these directives are basically these ones

for example, if we want to set a default policy to accept resources from self URL and base64 and only from mysite.com data we can set the policy like this:

Content-Security-Policy: "default-src 'self' data: https://mysite.com"

In case of the directives script-src and style-src, we have additional values to set like this ones:

<script>
  alert(‘Hi ;)’)
</script>

or in case of styles

<style>
  h1 {
    color: red;
  }
</style>

and in the case of script, we can limit the eval execution:

with the Eval Directive

Lets complement the last example of the policy allowing the css and js inline and allow eval in js the result is:

Content-Security-Policy: "default-src 'self' data: https://giorgiosaud.com; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'"

we can set special directives for any of them overlapping the default-src ones or set only the desired directives that we need, and that’s all.

Hoping that you know a little more about CSP see you later in another post and here is another interesting post about CORS and Preflight Request.

Link copied!

Comments for 000001