Search code examples
htmlreactjsmetacontent-security-policy

Including Content-Security-Policy in React


I want to include Content-Security-Policy to my React website. This is what I added to index.html in the head:

<meta http-equiv="Content-Security-Policy" content="default-src 'none';
      script-src 'self' 'unsafe-inline'
      https://www.google-analytics.com/
      https://maps.googleapis.com/
      https://developers.google.com/;
      img-src 'self'
      https://www.google-analytics.com
      https://maps.googleapis.com/
      https://maps.gstatic.com/
      https://developers.google.com/ data:;
      style-src 'self' https://fonts.googleapis.com 'unsafe-inline';
      font-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com data:;
      frame-src 'self' https://www.slideshare.net;
      upgrade-insecure-requests; block-all-mixed-content;
      connect-src 'self'">

I used this website- https://www.htbridge.com/websec/ to check if my website is secured and I still got 'F'. The problem is that I have many misconfiguration such that: X-FRAME-OPTIONS, X-XSS-PROTECTION, X-CONTENT-TYPE-OPTIONS and also CONTENT-SECURITY-POLICY. Am I doing something wrong or should I add more 'settings' to make it secure?


Solution

  • Content-Security-Policy is just one of the security measures to avoid some sort of attacks, and this can be used within the React index.html.

    However, the other methods you mentioned (X-Frame-Options, X-XSS-Protection, X-Content-Type-Options, etc) are essentially set in the server side when receiving http(s) requests.

    For instance, if the server hosting your React website is Apache, then you can add these lines in the '.htaccess' file:

    # Set Strict-Transport-Security
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" env=HTTPS
    
    # Set X-Frame-Options (Protect against page-framing and click-jacking)
    Header always append X-Frame-Options SAMEORIGIN
    
    # Set X-Content-Type-Options (Protect against content-sniffing)
    Header set X-Content-Type-Options nosniff
    
    # Set X-XSS-Protection (Protect against XSS attacks)
    Header set X-XSS-Protection "1; mode=block"
    
    # Set Referrer-Policy
    Header set Referrer-Policy "same-origin"