I learned about Content Security policy (CSP) while working on a project involving a Cordova mobile app which needed to communicate with a back end server I wrote in NodeJS. So I figured I would share with anyone running into this type of issue.
So when I had my server deployed at a url like http://x.y.z:8080
Without additional configuration, my app would not be able to communicate with the server successfully and I would get a blank screen or some other behavior I did not expect. When debugging (in this case using Safari developer tools because this was Cordova with iOS), I found the calls were getting blocked with this error
After referring to these documents,
- https://developers.google.com/web/fundamentals/security/csp/
- https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/
I did the following to resolve the issue
First I added code like this to my nodejs express app.js file to setup the server to send the correct Cross origin headers
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Then I configured my Cordova app's index page to allow access to this server using CSP, with something like this
<meta http-equiv="Content-Security-Policy" content="default-src 'self' http://x.y.z:8080/ 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Of course, tune the CSP settings to make sense and stay secure, for your project
This did it. Hope this is handy when you work on your next project. Happy coding!
Comments
Post a Comment