Search code examples
reactjsrecaptchacontent-security-policyhelmet.jsreact-google-recaptcha

react-google-recaptcha allow CSP


I'm using react js one of the forms I used react-google-captcha and worked perfectly when build and the backend I use helmet which provides CSP security and other errors came up

enter image description here

after searching to lot of sites i add the following meta tag

<meta
  http-equiv="Content-Security-Policy"
  content="script-src 'self' https://www.google.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/;
  frame-src https://www.google.com https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/"
/>

still no luck. have you encounter this problem? can share with me the solution. Thanks in advance

in my helmet configuration enter image description here


Solution

  • Helmet maintainer here.

    This is happening because of something called Content Security Policy, which Helmet sets by default. Helmet sets it in an HTTP header, which overrides what you've put in that <meta> tag.

    To solve your problem, you will need to configure Helmet's CSP.

    MDN has a good documentation about CSP which I would recommend reading for background. After that, take a look at Helmet's README to see how to configure its CSP component.

    To give some help specific to this question, let's take a look at one error you're seeing:

    Refused to load the script 'https://google.com/recaptcha/...' because it violates the following Content Security Policy directive: "script-src 'self'". ...
    

    This error is telling you that the script-src directive of your CSP does not allow JavaScript to load from google.com/recaptcha, and so it was blocked.

    There are several ways to fix this:

    1. Update your CSP to allow JavaScript to load from Google. You'd do something like this:

      app.use(
        helmet({
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "script-src": ["'self'", "google.com"],
            },
          },
        })
      );
      
    2. Refactor your app to avoid loading the CAPTCHA. Probably not possible, but it is an available solution.

    3. Disable CSP. This is the most dangerous option so I don't recommend it.

      app.use(
        helmet({
          contentSecurityPolicy: false,
        })
      );
      

    In summary: to solve your problem, you will need to tell Helmet to configure your CSP.