Search code examples
javajqueryajaxspring-bootcontent-security-policy

Getting CORS issue in API calling from AJAX


I am getting CORS issue while calling API from Ajax with header Content-Security-Policy":"frame-ancestors 'none'.

My APIs are built in Java spring boot. API server is already configured with Access-Control-Allow-Origin : *. If i remove Content-Security-Policy":"frame-ancestors 'none', the API is working perfectly fine.

Below is request :

$.ajax({url: "https://****.com/api/v2/login",
    type: 'post',
    data: JSON.stringify(domain),
    headers: {
      "x-dreamfactory-api-key":'*******',
      "x-frame-options":'deny',
      "Content-Security-Policy":"frame-ancestors 'none'",
      "pragma":'no-cache',
      "sec-fetch-mode":'cors',
      "Referer":'https://****.com',
      "origin":'https://****.com',
      "sec-fetch-site":'same-site',
      "sec-fetch-dest":'empty',
      "Content-Type":'application/json'
    },
    dataType: 'json',
    success: function (data) {
        console.log(JSON.stringify(data));
    }
  });

My API configuration using WebMVCConfigurationSupport below :

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/v2/**").allowedMethods("PATCH","GET", "POST", "OPTIONS","PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*").allowCredentials(true);
} 

Solution

  • Content-Security-Policy is a response header:

    The HTTP Content-Security-Policy response header allows website administrators to control resources the user agent is allowed to load for a given page.

    So it makes no sense to send it in an AJAX request.