user5443928
user5443928

Reputation:

Could not set the accurate content security policy in Angular4

I am getting the following error while setting the content-security-policy.

Error:

Refused to connect to 'http://localhost:3000/articles' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-eval' ws:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

I am explaining my code below.

<meta http-equiv="Content-Security-Policy" 
  content="default-src 'self' 'unsafe-eval' ws:;
  style-src 'self' 'unsafe-inline';
  script-src 'self' http://localhost:4200 'unsafe-inline' 'unsafe-eval';">

In my code I am also connecting to json server to read/write the data into json file which run at http://localhost:3000/articles but here I am getting those related error and this is my angular4 code. I need some help to resolve this error.

Upvotes: 0

Views: 1883

Answers (1)

woodykiddy
woodykiddy

Reputation: 6455

If I understand your question right, I think your angular app runs on localhost:4200 and the API service on localhost:3000? This would explain why you have got that CSP warning as the request is from different source according to your current CSP configuration.

Also, ideally, the CSP should be delivered via HTTP header which means you will need some kind of server backing to support that. For example, you can have a ASP.NET app that hosts the angular app and the CSP then can be configured via web.config file.

In your case, if it's purely frontend, then perhaps you could alter your CSP setting to something like this. Hopefully it works for you.

<meta http-equiv="Content-Security-Policy" 
  content="default-src 'self' http://localhost:3000/ 'unsafe-eval' ws:;
  style-src 'self' 'unsafe-inline';
  script-src 'self' http://localhost:4200 'unsafe-inline' 'unsafe-eval';">

Upvotes: 0

Related Questions