recaptcha-content-security-policy.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. <?php
  2. /**
  3. * BSD 3-Clause License
  4. * @copyright (c) 2019, Google Inc.
  5. * @link https://www.google.com/recaptcha
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions are met:
  10. * 1. Redistributions of source code must retain the above copyright notice, this
  11. * list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright notice,
  14. * this list of conditions and the following disclaimer in the documentation
  15. * and/or other materials provided with the distribution.
  16. *
  17. * 3. Neither the name of the copyright holder nor the names of its
  18. * contributors may be used to endorse or promote products derived from
  19. * this software without specific prior written permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  22. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  24. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  25. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. require __DIR__ . '/appengine-https.php';
  33. // Initiate the autoloader. The file should be generated by Composer.
  34. // You will provide your own autoloader or require the files directly if you did
  35. // not install via Composer.
  36. require_once __DIR__ . '/../vendor/autoload.php';
  37. // This example shows the use of a Content Security Policy
  38. // https://developers.google.com/web/fundamentals/security/csp/
  39. // First we generate a pseudorandom nonce for each included or inline script
  40. $nonce = base64_encode(openssl_random_pseudo_bytes(16));
  41. // Send the CSP header
  42. // Try commenting out the various lines to see what effect it has
  43. // NOTE: Always test your policy Content-Security-Policy-Report-Only first to
  44. // ensure you're not blocking any critical functionality. CSP is an important
  45. // security feature but you can break entire sections of your site if you
  46. // implement it incorrectly.
  47. header(
  48. "Content-Security-Policy: "
  49. ."default-src 'none'; " // By default we will deny everything
  50. ."script-src 'nonce-".$nonce."' 'strict-dynamic'; " // nonce allowing the reCAPTCHA library and other third-party scripts to be included
  51. ."img-src https://www.gstatic.com/recaptcha/ https://www.google-analytics.com; " // allow images from these URLS
  52. ."frame-src https://www.google.com/; " // allow frames from this URL
  53. ."style-src 'self'; " // allow style from our own origin
  54. ."connect-src 'self'; " // allow the fetch calls to our own origin
  55. );
  56. // Register API keys at https://www.google.com/recaptcha/admin
  57. $siteKey = '';
  58. $secret = '';
  59. // Copy the config.php.dist file to config.php and update it with your keys to run the examples
  60. if ($siteKey == '' && is_readable(__DIR__ . '/config.php')) {
  61. $config = include __DIR__ . '/config.php';
  62. $siteKey = $config['v3']['site'];
  63. $secret = $config['v3']['secret'];
  64. }
  65. // reCAPTCHA supports 40+ languages listed here: https://developers.google.com/recaptcha/docs/language
  66. $lang = 'en';
  67. // The v3 API lets you provide some context for the check by specifying an action.
  68. // See: https://developers.google.com/recaptcha/docs/v3
  69. $pageAction = 'examples/csp';
  70. ?>
  71. <!DOCTYPE html>
  72. <html lang="en">
  73. <meta charset="UTF-8">
  74. <meta name="viewport" content="width=device-width,height=device-height,minimum-scale=1">
  75. <link rel="shortcut icon" href="https://www.gstatic.com/recaptcha/admin/favicon.ico" type="image/x-icon"/>
  76. <link rel="canonical" href="https://recaptcha-demo.appspot.com/recaptcha-content-security-policy.php">
  77. <script type="application/ld+json">{ "@context": "http://schema.org", "@type": "WebSite", "name": "reCAPTCHA demo - Content Security Policy", "url": "https://recaptcha-demo.appspot.com/recaptcha-content-security-policy.php" }</script>
  78. <meta name="description" content="reCAPTCHA demo - Content Security Policy" />
  79. <meta property="og:url" content="https://recaptcha-demo.appspot.com/recaptcha-content-security-policy.php" />
  80. <meta property="og:type" content="website" />
  81. <meta property="og:title" content="reCAPTCHA demo - Content Security Policy" />
  82. <meta property="og:description" content="reCAPTCHA demo - Content Security Policy" />
  83. <link rel="stylesheet" type="text/css" href="/examples.css">
  84. <title>reCAPTCHA demo - Content Security Policy</title>
  85. <header>
  86. <h1>reCAPTCHA demo</h1><h2>Content Security Policy</h2>
  87. <p><a href="/">↩️ Home</a></p>
  88. </header>
  89. <main>
  90. <?php
  91. if ($siteKey === '' || $secret === ''):
  92. ?>
  93. <h2>Add your keys</h2>
  94. <p>If you do not have keys already then visit <kbd> <a href = "https://www.google.com/recaptcha/admin">https://www.google.com/recaptcha/admin</a></kbd> to generate them. Edit this file and set the respective keys in <kbd>$siteKey</kbd> and <kbd>$secret</kbd>. Reload the page after this.</p>
  95. <?php
  96. else:
  97. ?>
  98. <p>This example is sending the <kbd>Content-Security-Policy</kbd> header. Look at the source and inspect the network tab for this request to see what's happening. The reCAPTCHA v3 API is being called here, however you can use the same approach for the v2 API calls as well.</p>
  99. <p><strong>NOTE:</strong>This is a sample implementation, the score returned here is not a reflection on your Google account or type of traffic. In production, refer to the distribution of scores shown in <a href="https://www.google.com/recaptcha/admin" target="_blank">your admin interface</a> and adjust your own threshold accordingly. <strong>Do not raise issues regarding the score you see here.</strong></p>
  100. <ol id="recaptcha-steps">
  101. <li class="step0">reCAPTCHA script loading</li>
  102. <li class="step1 hidden"><kbd>grecaptcha.ready()</kbd> fired, calling <pre>grecaptcha.execute('<?php echo $siteKey; ?>', {action: '<?php echo $pageAction; ?>'})'</pre></li>
  103. <li class="step2 hidden">Received token from reCAPTCHA service, sending to our backend with:
  104. <pre class="token">fetch('/recaptcha-v3-verify.php?token=abc123</pre></li>
  105. <li class="step3 hidden">Received response from our backend: <pre class="response">{"json": "from-backend"}</pre></li>
  106. </ol>
  107. <p><a href="/recaptcha-content-security-policy.php">⤴️ Try again</a></p>
  108. <!-- Add the nonce for our inline script to this tag -->
  109. <script nonce="<?php echo $nonce; ?>">
  110. var onloadCallback = function() {
  111. const steps = document.getElementById('recaptcha-steps');
  112. grecaptcha.ready(function() {
  113. document.querySelector('.step1').classList.remove('hidden');
  114. grecaptcha.execute('<?php echo $siteKey; ?>', {action: '<?php echo $pageAction; ?>'}).then(function(token) {
  115. document.querySelector('.token').innerHTML = 'fetch(\'/recaptcha-v3-verify.php?action=<?php echo $pageAction; ?>&token=\'' + token;
  116. document.querySelector('.step2').classList.remove('hidden');
  117. fetch('/recaptcha-v3-verify.php?action=<?php echo $pageAction; ?>&token='+token).then(function(response) {
  118. response.json().then(function(data) {
  119. document.querySelector('.response').innerHTML = JSON.stringify(data, null, 2);
  120. document.querySelector('.step3').classList.remove('hidden');
  121. });
  122. });
  123. });
  124. });
  125. };
  126. </script>
  127. <!-- Add the nonce value for the reCAPTCHA library to its script tag -->
  128. <script async defer src="https://www.google.com/recaptcha/api.js?render=<?php echo $siteKey; ?>&onload=onloadCallback" nonce="<?php echo $nonce; ?>"></script>
  129. <?php
  130. endif;?>
  131. </main>
  132. <!-- Google Analytics - adding nonces here for the library and the inline code -->
  133. <script async defer src="https://www.googletagmanager.com/gtag/js?id=UA-123057962-1" nonce="<?php echo $nonce; ?>"></script>
  134. <script async nonce="<?php echo $nonce; ?>">window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-123057962-1');</script>