---
title: "Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP)"
published_at: "2020-08-12T10:00:02+00:00"
modified_at: "2025-11-06T12:43:55+00:00"
url: "https://www.syncfusion.com/blogs/post/asp-dotnet-mvc-content-security-policy"
excerpt: "Content Security Policy can be applied to protect your ASP.NET MVC apps from attackers. Steps to implement it are discussed here."
taxonomy_category:
  - "ASP.NET MVC"
  - "Development"
  - "Tips and Tricks"
  - "Web"
taxonomy_post_tag:
  - "ASP.NET MVC"
  - "development"
  - "security"
  - "Tips and Tricks"
  - "Web"
---

# Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP)

[Karthik Anandan](https://www.syncfusion.com/blogs/author/karthik-anandan)

![Shield Your ASP.NET MVC Web Applications with Content Security Policy (CSP)](https://www.syncfusion.com/blogs/wp-content/uploads/2020/08/Shield-Your-ASP.NET-MVC-Web-Applications-with-Content-Security-Policy-CSP.png)


**TL;DR:** Fortify your ASP.NET MVC web app against security threats by implementing Content Security Policy (CSP). Mitigate vulnerabilities like XSS and data injection attacks. Learn CSP directives, application methods, and best practices for testing and troubleshooting to secure your app today!

“**One single vulnerability is all an attacker needs**.”

– Window Snyder

Hackers are everywhere today. The world wide web is also a place for worldwide vulnerabilities. In order to safeguard your application, you need a powerful mechanism. In that case, [Content Security Policy](https://en.wikipedia.org/wiki/Content_Security_Policy)
 (CSP) is at your service with some excellent features.

In this blog post, we will see how to implement CSP in ASP.NET MVC web applications!

## Overview

CSP is used to protect your web application. It safeguards it by identifying some types of attacks like [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting)
 and SQL or data injection attacks.

**Note:** In CSP, some browser features are disabled by default.

If we want to apply CSP to our application, we have to define some CSP *content security* *directives* in the desired Content-Security-Policy headers or in the <meta> tags.

When a resource doesn’t match with the defined policy directives, then it won’t be loaded by the browser (scripts and styles from a third-party).

So if a policy restricts images means, then the browser will prevent images from loading when a page contains an <img> tag with a third-party origin in the img *src*attribute.

All latest versions of browsers [Chrome](https://www.google.com/intl/en_in/chrome/)
, [Edge](https://www.microsoft.com/en-us/edge)
, [Firefox](https://www.mozilla.org/en-US/firefox/)
, [Opera](https://www.opera.com/)
, and [Safari](https://www.apple.com/in/safari/)
 provide support for CSP.

## Topics to be covered

- [Policy directives.](#policy-directives)
- [Source List Reference.](#source-list-reference)
- [Apply the policy.](#apply-the-policy)
- [Test your policy.](#test-your-policy)
- [Browser supports.](#browser-supports)
- [Threats](#threats)
- [Troubleshoot](#troubleshoot)

## Policy directives

The CSP is used to restrict unauthorized third-party content resources. There are many directives available for a source (application). Once Content-Security-Policy headers are included in your application, the browser will reject any other content from sources that are not explicitly included or pre-approved using any of the directives.

You can add the directives in your ASP.NET web application’s HTTP [response header GUI in the IIS manager](https://support.microsoft.com/en-in/help/954002/how-to-add-a-custom-http-response-header-to-a-web-site-that-is-hosted)
 or add the following to your **Web.config** file.

```
<httpProtocol>
    <customHeaders>
       <add name="Content-Security-Policy" value="default-src 'self'" />
     </customHeaders>
</httpProtocol>
```

The following are some of the policy directives:

### default-src

default-src is used as a fallback if the directives (**object-src, img-src, etc.**) are not specified. Then, the ** default-src**content policy will be applied for source directives.

- Use **default-src ‘self’** to allow content from the current origin.
- Use **default-src ‘none’** to block everything that’s not added (pre- approved).

**Example:**

```
<add name="Content-Security-Policy" value="default-src 'self'" />
```

### script-src

script-src is used to pre-approve script sources.

1. Use **script-src ‘self’** to allow scripts from the current origin.
2. You can pre-approve your scripts using **script-src ‘https://www.example.com/scripts/*’**. It will allow domain scripts in this URL.
3. **script-src ‘*.googleapis.com www.example.*’** is used to allow all domain scripts.
4. Specify **unsafe-eval** to use eval () methods for creating code from strings.``` <add name="Content-Security-Policy" value="script-src 'self' 'unsafe-inline' 'unsafe-eval' 'https://www.example.com/scripts/*' '*.googleapis.com https://www.example.*’ " / > ```
5. **script-src ‘unsafe-inline’** is used to allow inline scripts. In this, you can write <script> </script> directly in the view. Don’t use inline script in your application directly. If you want to use inline script, you should use ** nonce** to avoid security vulnerabilities.``` <script nonce="r@nd0m"> doWhatever(); </script> <add name="Content-Security-Policy" value=" script-src ‘r@nd0m’" /> ``` ** Nonce browser support** The nonce directive is supported from CSP Level 2. It is supported by Chrome and Firefox after the version published in 2015, Safari 10+ or Edge 15+. It’s not supported in all Internet Explorer versions; you need to use the Edge browser for nonce support instead of Internet Explorer.

### **style-src**

style-src is used to pre-approve the CSS stylesheet sources.

1. Use **style-src ‘self’** to allow stylesheets from the current origin.
2. You can pre-approve your styles using **style-src ‘https://www.example.com/styles/*’**. It will allow domain styles in this URL.``` <add name="Content-Security-Policy" value=" style-src 'self' 'https://www.example.com/styles/*’ " / > ```

### object-src

object-src allows sources for the **<object>****,** **<embed>****,** and **<applet>** tags. You can specify ** object-src ‘none’** to prevent loading all URL sources.

```
<add name="Content-Security-Policy" value="object-src 'none'" / >
```

### img-src

img-src is used to restrict image sources. You can pre-approve third-party images in CSP by specifying the domain.

```
<add name="Content-Security-Policy" value="img-src 'none'" / >
```

### font-src

font-src is used to mention sources for loading fonts.

```
<add name="Content-Security-Policy" value="font-src 'none'" / >
```

### media-src

media-src is used to restrict sources from loading sound and video resources.

```
<add name="Content-Security-Policy" value="media-src 'none'" / >
```

### frame-ancestors

frame-ancestors is used to restrict URLs that can embed the current source in <iframe>, <object>.

```
<add name="Content-Security-Policy" value="frame-ancestors 'self'"/ >
```

### upgrade-insecure-requests

upgrade-insecure-requests indicates that the content URL from insecure (HTTP) sources should be acquired securely over HTTPS.

```
<add name="Content-Security-Policy" value="upgrade-insecure-requests">
```

## Source List Reference

| Source Value | Example | Description |
| --- | --- | --- |
| * | script-src ‘*’ | Allows any URL except data: blob: filesystem: schemes |
| ‘none’ | font-src ‘none’ | Doesn’t allow loading resources from any source. |
| ‘self’ | script-src ‘self’ | Allows loading resources from the same origin. |
| https: | style-src https: | Allows loading resources only over HTTPS on any domain. |
| data: | img-src ‘self’ data: | Allows loading resources via the data scheme (Base64 encoded images). |
| *.example.com | script-src ‘*.example.com’ | Allows loading resources from any subdomain under *.example.com |
| https://cdn.com | script-src ‘https://cdn.com’ | Allows loading resources only over HTTPS that matches the given domain. |
| ‘unsafe-inline’ | script-src ‘unsafe-inline’ | Allows inline source elements such as style attribute, onclick, or script tag bodies.<script> </script> and <style> </style> |
| ‘unsafe-eval’ | script-src ‘unsafe-eval’ | Allows unsafe dynamic code evaluation such as JavaScript eval (). |
| ‘nonce-‘ | script-src ‘nonce-r@nd0m’ | Allows inline script or CSS to execute if the script (<script nonce = “r@nd0m ” >) tag contains a nonce attribute matching the nonce specified in the CSP header.The nonce should be a secure random string and should not be reused. It is applicable from CSP Level 2. |
| ‘strict-dynamic’ | script-src ‘strict-dynamic’ | Allows script to load additional scripts via non-“parser-inserted” script elements (document.createElement(‘script’); is allowed). It is applicable from CSP Level 3. |

## Apply the policy

Use <system.webServer> tag to apply the CSP.

Place the directives in the name attribute value. Separate directives with a semicolon (;). Refer to the following code example.

```
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Content-Security-Policy" value="upgrade-insecure-requests; default-src 'self'; style-src 'self'; script-src 'self'; img-src 'none'; frame-ancestors 'self'" />
        </customHeaders>
    </httpProtocol>
</system.webServer>
```

## Test your policy

After implementing the CSP in your application, you can validate your CSP directives. It helps to confirm that third-party scripts are not inadvertently blocked. If any of the CSP have failed in your application, you can generate a report to rectify them.

For more information, see [MDN web docs: Content-Security-Policy-Report-Only](https://developer.mozilla.org/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only)
and [Google CSP evaluator](https://csp-evaluator.withgoogle.com/)
.

## Browser supports

CSP supports all latest versions of modern browsers but not Internet Explorer at all. Refer to the following links.

- [Browser support list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#Browser_compatibility)
- [CSP level](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#Specifications)

## Threats

There are many open tools available to scan your application. [OWASP](https://owasp.org/www-project-zap/)
 is one of the finest applications for finding security vulnerabilities. Once you implement the CSP, you can scan your complete application. This will not affect your application’s performance. You can also scan your production site for:

- [Cross-site scripting](https://www.syncfusion.com/blogs/post/10-practices-secure-asp-net-core-mvc-app.aspx#cross-site-scripting)
- [SQL/data injection](https://www.syncfusion.com/blogs/post/10-practices-secure-asp-net-core-mvc-app.aspx#SQL-injection)

See more about security vulnerabilities [here](https://www.syncfusion.com/blogs/post/10-practices-secure-asp-net-core-mvc-app.aspx)
.

## Troubleshoot

If CSP is not implemented properly in your application, the errors will appear in your browser console. The browser will provide the details about the scripts that are blocked by your webpage. It will also provide the details like:

- 
  - How to change the policy to allow a blocked item.
  - Elements that don’t accept the policy.

**Note:** CSP is only effective when the client’s browser supports all the included directives. For the latest browser support matrix, check [Can I use: Content-Security-Policy](https://caniuse.com/#search=Content-Security-Policy)
.

## Conclusion

In this blog, we have seen the steps to implement Content Security Policy (CSP) in your ASP.NET MVC web applications. I hope this blog post was helpful to you.

Syncfusion provides [80+ ASP.NET Core](https://www.syncfusion.com/aspnet-core-ui-controls)
, and [ASP.NET MVC UI controls](https://www.syncfusion.com/aspnet-mvc-ui-controls)
 for web application development. We encourage you to take a moment to learn about our products and browse our [interactive demos](https://ej2.syncfusion.com/home/aspnetcore.html)
.

For existing customers, the latest version of our products is available for download from the [License and Downloads](https://www.syncfusion.com/account/downloads)
 page. If you are not yet a Syncfusion customer, you can try our 30-day [free trial](https://www.syncfusion.com/downloads)
 to check out our available features. Also, try our samples from this [GitHub](https://github.com/syncfusion)
 location.

For questions, you can contact us through our [support forum](https://www.syncfusion.com/forums)
, [support portal](https://support.syncfusion.com/)
, or [feedback portal](https://www.syncfusion.com/feedback)
. We are always happy to assist you!

## Related blogs

- [Easily Publish an ASP.NET Core App in Linux Docker that Compresses PDF Documents](https://www.syncfusion.com/blogs/post/easily-publish-an-asp-net-core-app-in-linux-docker-that-compresses-pdf-documents.aspx)
- [How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware](https://www.syncfusion.com/blogs/post/how-to-migrate-asp-net-http-handlers-and-modules-to-asp-net-core-middleware.aspx)
- [Create Report Viewer Component in Angular app with ASP.NET Core](https://www.syncfusion.com/blogs/post/create-report-viewer-component-in-angular-app-with-asp-net-core.aspx)
- [Easily Perform LINQ Mocking to Unit Test ASP.NET Core Application](https://www.syncfusion.com/blogs/post/linq-mocking-in-asp-net-core.aspx)
