The Content-Security-Policy allow the browser to detect and mitigate attacks including (but not limited to) cross site scripting and data injection.

With CSP you can lock down your application by reduce the privilege of the application. You control what resources that can be loaded and whitelists what sources that are allowed to do so.

There are a lot of different directives to specify. Here are some of them:

  • default-src fallback policy, all unspecified directives will use this
  • style-src restricts the locations from where styles can applied from
  • script-src restricts the locations from where scripts can be executed
  • form-action restricts what targets from a form submission that is allowed
  • and more …

The whole list can be found on the specification:

The X-Frame-Options HTTP header is obsoleted by the frame-ancestors directive. If both are used the X-Frame-Options are ignored. But keep both in place if you would like to support security on older browsers.

With every directive you state one or more allowed sources like:

A complete list can be found on the same site as the directives:

An other great resource for all directives and sources are: but at the time of writing this, it doesn’t include the Level 3 of the standard. Level 3 is a working draft but is backward compatible.

You can enable reporting by adding the report-to directive, but since this belongs to the Level 3 specification and not all browsers have implemented that yet you also need to add the deprecated report-uri directive. When a violation happens on a live site you will get information about it. You need an endpoint to handle this and if you don’t like to set it up yourself I would recommend using

It can be tricky to set up a new policy or just tightening up an existing one. This is when the security header Content-Security-Policy-Report-Only comes in handy. It can be used side by side with Content-Security-Policy and have the same mechanism except for one thing: It will not enforce the restrictions only report them when they are violated. Don’t forget the report-to/report-uri directives.

To know if your CPS are good or not you can use: to validate it.

Please take note on that this header is primary a defense mechanism that limits the harm if/when your site are under attack not a way to stop attacks. So remember to always validate your input and encode your output to limit your attack area.

Adding it can look like this:

<add name="Content-Security-Policy" value="default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';"/>

Read more about: How to add headers to your .net site

Previously in the Security Headers series: Referrer-Policy