Cordova security policy trying to get json data from api
jquery-1.11.1.min.js:4 Refused to connect to
'https://xxxxxxxx/v1/common/introductions/faqs' because it
violates the following Content Security Policy directive: "default-src
'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Note that
'connect-src' was not explicitly set, so 'default-src' is used as a
fallback.
This is the error I am getting when executing this jquery for my cordova app
$(document).ready(function(){
$("#FAQS").html("Hello worldss!");
alert("rajesh");
$.getJSON("https://xxxxxxxxx/v1/common/introductions/faqs",
function(result)
{
$("#FAQS").html(result['faq'][0]);
alert("hi");
})
});
Here is my security policy in my index.html
<meta http-equiv="Content-Security-Policy" content="default-src 'self'
data: gap: https://ssl.gstatic.com 'unsafe-eval'; connect-src 'self'
https://xxxxxxxx/v1/common/introductions/faqs; style-src 'self'
'unsafe-inline'; media-src *">
I faced many issues on Cordova Stack Overflow - Denied to connect to api from device (content security policy)
but couldn't display my json data and it shows the same error
source to share
Check out the following example from html5rocks :
If you want to whitelist the code from https://apis.google.com/js/plusone.js
, you need to add the source hostname to your CSP like this:
script-src 'self' https://apis.google.com
Thus, to allow access to https://xxxxxxxx/v1/common/introductions/faqs
, you need to add the corresponding hostname to your CSP:
connect-src 'self' https://xxxxxxxx
The complete CSP might look like this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'
data: gap: https://ssl.gstatic.com 'unsafe-eval'; connect-src 'self'
https://xxxxxxxx; style-src 'self'
'unsafe-inline'; media-src *">
Also see Mozilla 's documentation for the connect-src directive. It clearly states what the source host should look like:
Internet hosts by name or IP address, and an optional URL scheme and / or port number. The site address can include an optional leading wildcard (asterisk, '*'), and you can use the wildcard ("*" again) as the port number to indicate that all valid ports are valid for the source.
source to share
You must be using a newer version of jquery first.
Second, you need to set an access policy on the server to allow CORS from your frontend ...
in php looks like this:
<?php
header("Access-Control-Allow-Origin: *");
you can learn how to do it in other languages ββhere: https://enable-cors.org
Thirdly. are you using nginx as your web server or as a reverse proxy? If it is the latter, you will need to check your nginx xconfig.
source to share