/  Technology   /  Content security policy in React app didn’t block online script
c1

Content security policy in React app didn’t block online script

 

Actually you don’t need a Package to achieve that, you can just add a <meta> tag as your first element to <head> block inside index.html founded in public folder.

 

As for jQuery issue, my guess that maybe a hash / nonce that auto generated by CSP-html-webpack-plugin is referring to jQuery which could lead to allow it?

 

Also, please note that using unsafe-eval , eval is considered unsafe and it’s should be avoided.

 

With that in mind, please note that if you’re going to test your app security in some online security tools. it will basically Fail. Yes, adding a <meta> security tags could be enough for basic protection though, you may consider using server-side HTTP Headers for other security vulnerabilities. Actually meta tag is not needed and it’s optional.

 

For instance, as for CSP policies, I’ve deployed a test react app using <meta> method, when testing on immuniweb.com or gf.dev, you’ll see that there is No CSP policy! though, it works fine and see test Here

 

So if you can configure your server environment and I encourage you to do that. You could use Express with ‘express-csp-header’ or/and using Nginx as a reverse proxy.

 

If you can’t, try setting your <meta> its easy:

 

Syntax will be:

<meta http-equiv="Content-Security-Policy" content="directive 'source';"

Just like key and value pair where directives are the keys. i.e. script-src, style-src, base-uri,  and sources (with single quotations marks ‘ ‘) are the values i.e. self, none, unsafe-inline.

 

For example since you’re using React and React is using inline scripts , you will need to add ‘unsafe-inline’ to your script directive like so:

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self'; base-uri 'self';">

If you were to add some inline CSS or going to use a library like styled-components, you will need to add ‘unsafe-inline’ to your style directive or files as well:

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; base-uri 'self';">

External URLs like google font or analytics:

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' www.google-analytics.com 'unsafe-inline'; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com; base-uri 'self';">

 

Leave a comment