reCAPTCHA with Content Security Policy

前端 未结 3 392
孤街浪徒
孤街浪徒 2020-12-08 21:39

I\'m trying to make reCAPTCHA work along with a strict Content Security Policy. This is the basic version I have, which works correctly:

HTML



        
相关标签:
3条回答
  • 2020-12-08 22:26

    I no not believe reCAPTCHA supports CSP without allowing inline styles. I found this open issue in the reCAPTCHA Github repository.

    This sample page with reCAPTCHA using CSP works because it does not define style-src or default-src. An inspection of the page's DOM reveals this inserted div:

    <div class="g-recaptcha" data-sitekey="6LdOLRgTAAAAAPYECt9KLIL_LLwOuuuHAUw7QUTm">
        <div style="width: 304px; height: 78px;">
            <div>
                <iframe src="https://www.google.com/recaptcha/api2/anchor?k=6LdOLRgTAAAAAPYECt9KLIL_LLwOuuuHAUw7QUTm&amp;co=aHR0cHM6Ly9jc3AtZXhwZXJpbWVudHMuYXBwc3BvdC5jb206NDQz&amp;hl=en&amp;v=r20160926121436&amp;size=normal&amp;cb=g72al0v10dxg" title="recaptcha widget" width="304" height="78" role="presentation" frameborder="0" scrolling="no" name="undefined"></iframe>
            </div>
            <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none;  display: none; "></textarea>
        </div>
    </div>
    

    The inline style for textarea evaluates to MammJ3J+TGIHdHxYsGLjD6DzRU0ZmxXKZ2DvTePAF0o= as determined by:

    echo -n "width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none;  display: none; " | openssl dgst -sha256 -binary | base64
    

    This matches the hash indicated in your error message. However, including the hash in style-src does not work for inline styles in Chrome per this open bug. It appears this will be supported with unsafe-hashed-attributes which as far as I can tell hasn't made it to a Chrome release.

    For what it's worth, adding the hash makes it work in Firefox.

    0 讨论(0)
  • 2020-12-08 22:28

    The reCAPTCHA service has been updated so style-src 'unsafe-inline' is not required anymore. Below HTML and HTTP headers should work per this closed issue:

    HTML:

    <script src="https://www.google.com/recaptcha/api.js?render=site-key" nonce="{NONCE}"></script>
    

    HTTP Header:

    Content-Security-Policy: default-src 'self'; script-src 'nonce-{NONCE}'; img-src www.gstatic.com; frame-src www.google.com; object-src 'none'; base-uri 'none';
    
    0 讨论(0)
  • 2020-12-08 22:28

    use below code in the web.config file for ASp.Net applications.

    <child-src>
          <add source="www.google.com"/>
    

    0 讨论(0)
提交回复
热议问题