1658392080
By ARCANEDEV©
reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis engine to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.
v2
(+ Invisible) & v3
reCaptcha are supported.4.2
to 9.x
are supported.To use reCAPTCHA, you need to have a site key
and a secret key
. Click here to setup a domain and get your keys.
The site key
is using for the widget and the secret key
is used to validate the response we get from Google.
For more details, check the official documentation.
Laravel | noCaptcha |
---|---|
Note : This is a framework-agnostic package, so you can use any version of this package in your PHP project.
You can install this package via Composer by running this command composer require arcanedev/no-captcha
.
NOTE : The package will automatically register itself if you're using Laravel
>= v5.5
, so you can skip this section.
Once the package is installed, you can register the service provider in config/app.php
in the providers
array:
'providers' => [
...
Arcanedev\NoCaptcha\NoCaptchaServiceProvider::class,
],
For Laravel 4.2 (PHP 5.4), the config file is located in
app/config/app.php
In the providers
array:
'providers' => [
...
'Arcanedev\NoCaptcha\Laravel\ServiceProvider',
],
There is not really a need to publish the configuration file. Both the secret
and sitekey
should be set in your environment file so it won't be available in your versioning system.
See Environment Configuration documentation.
// Edit your .env file by adding this two lines and fill it with your keys.
NOCAPTCHA_SECRET=your-secret-key
NOCAPTCHA_SITEKEY=your-site-key
For Laravel 4.2: Protecting Sensitive Configuration
Run php artisan vendor:publish --provider="Arcanedev\NoCaptcha\NoCaptchaServiceProvider"
to publish the config file.
Edit the secret
and sitekey
values in config/no-captcha.php
file:
For Laravel 4.2, run
php artisan config:publish arcanedev/no-captcha
and the file is located inapp/config/packages/arcanedev/no-captcha/config.php
.
Checkout example below:
<?php
require_once(__DIR__.'/vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV2;
$secret = 'your-secret-key';
$sitekey = 'your-site-key';
$captcha = new NoCaptchaV2($secret, $sitekey);
if ($_POST) {
// You need to check also if the $_POST['g-recaptcha-response'] is not empty.
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form action="?" method="POST">
<?php echo $captcha->display(); ?>
<button type="submit">Submit</button>
</form>
<?php
// At the bottom, before the </body> (If you're a good programmer and you listen to your mother)
echo $captcha->script();
?>
Note: The NoCaptcha
constructor accepts four arguments:
Argument | Required | Description |
---|---|---|
$secret | Yes | Your secret key. |
$siteKey | Yes | Your site key. |
$lang | No | You can specify your language. |
$attributes | No | You can specify a global attributes for your captchas. |
Check the examples folder for more usage details.
The code below explains how to enable and customize the invisible reCAPTCHA on your webpage.
require_once(__DIR__ . '/../vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV2;
$secret = 'your-secret-key';
$sitekey = 'your-site-key';
$captcha = new NoCaptchaV2($secret, $sitekey);
if ($_POST) {
// You need to check also if the $_POST['g-recaptcha-response'] is not empty.
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form method="POST" id="demo-form">
<?php echo $captcha->button('Send', ['data-badge' => 'inline']); ?>
</form>
<?php echo $captcha->script(); ?>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
NOTE : You need to specify the invisible version in your captcha admin page. Check this page for more details: https://developers.google.com/recaptcha/docs/versions
The code below shows you how to use the ReCaptcha V3:
<?php
require_once(__DIR__.'/vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV3;
$captcha = new NoCaptchaV3(
'SECRET-KEY',
'SITE-KEY'
);
if ($_POST) {
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form method="POST">
<input type="email" name="email"><br>
<button type="submit">Submit</button>
<?php echo $captcha->input('g-recaptcha-response'); ?>
</form>
<?php echo $captcha->script(); ?>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('SITE-KEY', {action: 'homepage'});
});
</script>
Insert reCAPTCHA inside your form using one of this examples:
By using Blade syntax
{!! Form::open([...]) !!}
// Other inputs...
{!! no_captcha()->display() !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
// Remember what your mother told you
{!! no_captcha()->script() !!}
For Laravel 4.2, use
{{ ... }}
instead of{!! ... !!}
Without using Blade syntax
<?php
echo Form::open([...]);
// Other inputs...
echo no_captcha()->display()->toHtml();
echo Form::submit('Submit');
echo Form::close();
?>
<?php echo no_captcha()->script()->toHtml(); ?>
To validate the response we get from Google, your can use the captcha
rule in your validator:
use Arcanedev\NoCaptcha\Rules\CaptchaRule;
$inputs = Input::all();
$rules = [
// Other validation rules...
'g-recaptcha-response' => ['required', new CaptchaRule],
];
$messages = [
'g-recaptcha-response.required' => 'Your custom validation message.',
'g-recaptcha-response.captcha' => 'Your custom validation message.',
];
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages();
var_dump($errors->first('g-recaptcha-response'));
// Redirect back or throw an error
}
If you want to manage the localized messages, edit the validation.php
files inside your lang directory.
For example:
// resources/lang/en/validation.php
return [
...
// Add this line with your custom message
'captcha' => "If you read this message, then you're a robot.",
];
// resources/lang/fr/validation.php
return [
...
// Ajoutez cette ligne avec votre message personnalisé
'captcha' => 'Si vous lisez ce message, alors vous êtes un robot.',
];
For the required
rule, you can customize it by adding your messages to custom
array in the resources/lang/xx/validation.php
:
'custom' => [
'g-recaptcha-response' => [
'required' => 'Your custom validation message for captchas.',
],
],
For Laravel 4.2, the lang folder is located in
app/lang
use Arcanedev\NoCaptcha\Rules\CaptchaRule;
$validator = Validator::make(Input::all(), [
// Other validation rules...
'g-recaptcha-response' => ['required', new CaptchaRule],
]);
if ($validator->fails()) {
$errors = $validator->messages();
var_dump($errors->first('g-recaptcha-response'));
// Redirect back or throw an error
}
For more advanced usage, check the official recaptcha documentation.
Attributes | Value | Default | Description |
---|---|---|---|
data-sitekey | Your sitekey | ||
data-theme | dark / light | light | Optional. The color theme of the widget. |
data-type | audio / image | image | Optional. The type of CAPTCHA to serve. |
data-size | compact / normal | normal | Optional. The size of the widget. |
data-tabindex | 0 | Optional. The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier. | |
data-callback | Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. The user's response, g-recaptcha-response , will be the input for your callback function. | ||
data-expired-callback | Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. |
Attributes | Value | Default | Description |
---|---|---|---|
data-sitekey | Your sitekey | ||
data-badge | bottomleft / inline / bottomright | bottomright | Optional. Reposition the reCAPTCHA badge. 'inline' allows you to control the CSS. |
data-type | audio / image | image | Optional. The type of CAPTCHA to serve. |
data-size | compact / normal | normal | Optional. The size of the widget. |
data-tabindex | Optional. The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier. | ||
data-callback | onSubmit | Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. The user's response, g-recaptcha-response , will be the input for your callback function. |
Check the examples folder for more usage details.
Any ideas are welcome. Feel free to submit any issues or pull requests, please check the contribution guidelines.
If you discover any security related issues, please email arcanedev.maroc@gmail.com instead of using the issue tracker.
Author: ARCANEDEV
Source Code: https://github.com/ARCANEDEV/noCAPTCHA
License: MIT license
1658392080
By ARCANEDEV©
reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis engine to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.
v2
(+ Invisible) & v3
reCaptcha are supported.4.2
to 9.x
are supported.To use reCAPTCHA, you need to have a site key
and a secret key
. Click here to setup a domain and get your keys.
The site key
is using for the widget and the secret key
is used to validate the response we get from Google.
For more details, check the official documentation.
Laravel | noCaptcha |
---|---|
Note : This is a framework-agnostic package, so you can use any version of this package in your PHP project.
You can install this package via Composer by running this command composer require arcanedev/no-captcha
.
NOTE : The package will automatically register itself if you're using Laravel
>= v5.5
, so you can skip this section.
Once the package is installed, you can register the service provider in config/app.php
in the providers
array:
'providers' => [
...
Arcanedev\NoCaptcha\NoCaptchaServiceProvider::class,
],
For Laravel 4.2 (PHP 5.4), the config file is located in
app/config/app.php
In the providers
array:
'providers' => [
...
'Arcanedev\NoCaptcha\Laravel\ServiceProvider',
],
There is not really a need to publish the configuration file. Both the secret
and sitekey
should be set in your environment file so it won't be available in your versioning system.
See Environment Configuration documentation.
// Edit your .env file by adding this two lines and fill it with your keys.
NOCAPTCHA_SECRET=your-secret-key
NOCAPTCHA_SITEKEY=your-site-key
For Laravel 4.2: Protecting Sensitive Configuration
Run php artisan vendor:publish --provider="Arcanedev\NoCaptcha\NoCaptchaServiceProvider"
to publish the config file.
Edit the secret
and sitekey
values in config/no-captcha.php
file:
For Laravel 4.2, run
php artisan config:publish arcanedev/no-captcha
and the file is located inapp/config/packages/arcanedev/no-captcha/config.php
.
Checkout example below:
<?php
require_once(__DIR__.'/vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV2;
$secret = 'your-secret-key';
$sitekey = 'your-site-key';
$captcha = new NoCaptchaV2($secret, $sitekey);
if ($_POST) {
// You need to check also if the $_POST['g-recaptcha-response'] is not empty.
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form action="?" method="POST">
<?php echo $captcha->display(); ?>
<button type="submit">Submit</button>
</form>
<?php
// At the bottom, before the </body> (If you're a good programmer and you listen to your mother)
echo $captcha->script();
?>
Note: The NoCaptcha
constructor accepts four arguments:
Argument | Required | Description |
---|---|---|
$secret | Yes | Your secret key. |
$siteKey | Yes | Your site key. |
$lang | No | You can specify your language. |
$attributes | No | You can specify a global attributes for your captchas. |
Check the examples folder for more usage details.
The code below explains how to enable and customize the invisible reCAPTCHA on your webpage.
require_once(__DIR__ . '/../vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV2;
$secret = 'your-secret-key';
$sitekey = 'your-site-key';
$captcha = new NoCaptchaV2($secret, $sitekey);
if ($_POST) {
// You need to check also if the $_POST['g-recaptcha-response'] is not empty.
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form method="POST" id="demo-form">
<?php echo $captcha->button('Send', ['data-badge' => 'inline']); ?>
</form>
<?php echo $captcha->script(); ?>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
NOTE : You need to specify the invisible version in your captcha admin page. Check this page for more details: https://developers.google.com/recaptcha/docs/versions
The code below shows you how to use the ReCaptcha V3:
<?php
require_once(__DIR__.'/vendor/autoload.php');
use Arcanedev\NoCaptcha\NoCaptchaV3;
$captcha = new NoCaptchaV3(
'SECRET-KEY',
'SITE-KEY'
);
if ($_POST) {
$response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);
echo $response->isSuccess()
? 'Yay ! You are a human.'
: 'No ! You are a robot.';
exit();
}
?>
<form method="POST">
<input type="email" name="email"><br>
<button type="submit">Submit</button>
<?php echo $captcha->input('g-recaptcha-response'); ?>
</form>
<?php echo $captcha->script(); ?>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('SITE-KEY', {action: 'homepage'});
});
</script>
Insert reCAPTCHA inside your form using one of this examples:
By using Blade syntax
{!! Form::open([...]) !!}
// Other inputs...
{!! no_captcha()->display() !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
// Remember what your mother told you
{!! no_captcha()->script() !!}
For Laravel 4.2, use
{{ ... }}
instead of{!! ... !!}
Without using Blade syntax
<?php
echo Form::open([...]);
// Other inputs...
echo no_captcha()->display()->toHtml();
echo Form::submit('Submit');
echo Form::close();
?>
<?php echo no_captcha()->script()->toHtml(); ?>
To validate the response we get from Google, your can use the captcha
rule in your validator:
use Arcanedev\NoCaptcha\Rules\CaptchaRule;
$inputs = Input::all();
$rules = [
// Other validation rules...
'g-recaptcha-response' => ['required', new CaptchaRule],
];
$messages = [
'g-recaptcha-response.required' => 'Your custom validation message.',
'g-recaptcha-response.captcha' => 'Your custom validation message.',
];
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages();
var_dump($errors->first('g-recaptcha-response'));
// Redirect back or throw an error
}
If you want to manage the localized messages, edit the validation.php
files inside your lang directory.
For example:
// resources/lang/en/validation.php
return [
...
// Add this line with your custom message
'captcha' => "If you read this message, then you're a robot.",
];
// resources/lang/fr/validation.php
return [
...
// Ajoutez cette ligne avec votre message personnalisé
'captcha' => 'Si vous lisez ce message, alors vous êtes un robot.',
];
For the required
rule, you can customize it by adding your messages to custom
array in the resources/lang/xx/validation.php
:
'custom' => [
'g-recaptcha-response' => [
'required' => 'Your custom validation message for captchas.',
],
],
For Laravel 4.2, the lang folder is located in
app/lang
use Arcanedev\NoCaptcha\Rules\CaptchaRule;
$validator = Validator::make(Input::all(), [
// Other validation rules...
'g-recaptcha-response' => ['required', new CaptchaRule],
]);
if ($validator->fails()) {
$errors = $validator->messages();
var_dump($errors->first('g-recaptcha-response'));
// Redirect back or throw an error
}
For more advanced usage, check the official recaptcha documentation.
Attributes | Value | Default | Description |
---|---|---|---|
data-sitekey | Your sitekey | ||
data-theme | dark / light | light | Optional. The color theme of the widget. |
data-type | audio / image | image | Optional. The type of CAPTCHA to serve. |
data-size | compact / normal | normal | Optional. The size of the widget. |
data-tabindex | 0 | Optional. The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier. | |
data-callback | Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. The user's response, g-recaptcha-response , will be the input for your callback function. | ||
data-expired-callback | Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. |
Attributes | Value | Default | Description |
---|---|---|---|
data-sitekey | Your sitekey | ||
data-badge | bottomleft / inline / bottomright | bottomright | Optional. Reposition the reCAPTCHA badge. 'inline' allows you to control the CSS. |
data-type | audio / image | image | Optional. The type of CAPTCHA to serve. |
data-size | compact / normal | normal | Optional. The size of the widget. |
data-tabindex | Optional. The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier. | ||
data-callback | onSubmit | Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. The user's response, g-recaptcha-response , will be the input for your callback function. |
Check the examples folder for more usage details.
Any ideas are welcome. Feel free to submit any issues or pull requests, please check the contribution guidelines.
If you discover any security related issues, please email arcanedev.maroc@gmail.com instead of using the issue tracker.
Author: ARCANEDEV
Source Code: https://github.com/ARCANEDEV/noCAPTCHA
License: MIT license
1671876604
Google reCAPTCHA v3 is an invisible type of captcha where the user doesn’t have to interact. It tracks the user behavior on the site and returns a score between 0 to 1 with the response.
This score is use for validation on the server side.
In this tutorial, I show how you can add Google reCAPTCHA v3 to your form in CodeIgniter 4.
You can skip this step if you already registered for Google reCAPTCHA v3 and have site and secret keys.
localhost
if you want to test it on your local system.Accept the reCAPTCHA Terms of Service
and click the Submit button..env
file which is available at the project root.NOTE – If dot (.) not added at the start then rename the file to .env.
GOOGLE_RECAPTCHAV3_SITEKEY = 6LdP-nIhAAAAAA6rzq7BTh_jKqIYeKMoaALxkKte
GOOGLE_RECAPTCHAV3_SECRETKEY = 6LdV-nIhAAAAAL-uFI4w9kQUaqMkeU2K3KojlXyE
.env
file.security.tokenName
,security.headerName
, security.cookieName
, security.expires
,and security.regenerate
.security.tokenName
value with 'csrf_hash_name'
. With this name read CSRF hash. You can update it with any other value.security.regenerate = false
.security.tokenName = 'csrf_hash_name'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie_name'
security.expires = 7200
security.regenerate = true
app/Config/Filters.php
file.'csrf'
in 'before'
if commented.// Always applied before every request
public $globals = [
'before' => [
// 'honeypot',
'csrf',
// 'invalidchars',
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
Create a rule to verify reCaptcha v3 response.
CaptchaValidation.php
file in app/Config/
folder.CaptchaValidation
class.verifyrecaptchaV3()
method. Here, the method name is also a rule name..env
file and assign it to $secretkey
.https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$str."&remoteip=".$_SERVER['REMOTE_ADDR']
$responseData->success
is true
and $responseData->score
is >
0.6 then return true
otherwise, assign error message in $error
and return false
.NOTE – You can update value of
$score
from 0.6 to any other value. Make sure to set it between 0.5 to 1.
Completed Code
<?php
namespace Config;
class CaptchaValidation{
public function verifyrecaptchaV3(string $str, ?string &$error = null): bool
{
$secretkey = getenv('GOOGLE_RECAPTCHAV3_SECRETKEY');
if(($str) && !empty($str)) {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$str."&remoteip=".$_SERVER['REMOTE_ADDR']);
$responseData = json_decode($response);
$score = 0.6; // 0 - 1
if($responseData->success && $responseData->score > $score) { // Verified
return true;
}
}
$error = "Invalid captacha";
return false;
}
}
To use the above-created validation rule need to define it in the Validation.php
file.
app/Config/Validation.php
file.Config\CaptchaValidation
class.CaptchaValidation::class
in $ruleSets
Array.Completed Code
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\CreditCardRules;
use CodeIgniter\Validation\FileRules;
use CodeIgniter\Validation\FormatRules;
use CodeIgniter\Validation\Rules;
use Config\CaptchaValidation; // Custom reCAPTCHA v3 validation
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var string[]
*/
public $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
CaptchaValidation::class, // Custom reCAPTCHA v3 validation
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}
Create PagesController
Controller –
php spark make:controller PagesController
app/Controllers/PagesController.php
file.index
view.Validate the submitted values. Here, for validating recaptcha specify – 'recaptch_response' => 'required|verifyrecaptchaV3',
.
verifyrecaptchaV3
is a custom validation rule created in the previous step.
If <form >
is not validated then return to the page with error messages otherwise store the success message in SESSION flash and redirect to route('/')
.
Completed Code
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class PagesController extends BaseController
{
public function index(){
return view('index');
}
public function submitContactUs(){
// Validation
$input = $this->validate([
'name' => 'required',
'email' => 'required',
'subject' => 'required',
'message' => 'required',
'recaptcha_response' => 'required|verifyrecaptchaV3',
],[
'recaptcha_response' => [
'required' => 'Please verify captcha',
],
]);
if (!$input) { // Not valid
$data['validation'] = $this->validator;
return redirect()->back()->withInput()->with('validation', $this->validator);
}else{
// Set Session
session()->setFlashdata('message', 'Request Submitted Successfully!');
session()->setFlashdata('alert-class', 'alert-success');
}
return redirect()->route('/');
}
}
app/Config/Routes.php
file.$routes->get('/', 'PagesController::index');
$routes->post('page/submitContactUs', 'PagesController::submitContactUs');
index.php
file in app/Views/
folder.<head >
section –<!-- reCAPTCHA JS-->
<script src="https://www.google.com/recaptcha/api.js?render=<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>"></script>
Here, also specify sitekey.
action
URL to <?=site_url('page/submitContactUs')?>
. Define onSubmit
event on <form >
that calls onSubmit(event)
.<form>
element is not validated. In the <form >
also display an error message if recaptcha is not validated.#recaptcha_response
to store recapatcha token response on <form >
submit.Script
onSubmit()
function that calls on <form >
submit.grecaptcha.execute
on submit
action to get a token.#recaptcha_response
.<form >
.Completed Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to add Google reCAPTCHA v3 in CodeIgniter 4</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >
<!-- reCAPTCHA JS-->
<script src="https://www.google.com/recaptcha/api.js?render=<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>"></script>
<!-- Include script -->
<script type="text/javascript">
function onSubmit(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute("<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>", {action: 'submit'}).then(function(token) {
// Store recaptcha response
document.getElementById("recaptcha_response").value = token;
// Submit form
document.getElementById("contactForm").submit();
});
});
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5" style="margin: 0 auto;">
<?php
// Display Response
if(session()->has('message')){
?>
<div class="alert <?= session()->getFlashdata('alert-class') ?>">
<?= session()->getFlashdata('message') ?>
</div>
<?php
}
?>
<h2 class="mb-4">Contact US</h2>
<?php $validation = \Config\Services::validation(); ?>
<form id="contactForm" method="post" action="<?=site_url('page/submitContactUs')?>" onSubmit="onSubmit(event)">
<?= csrf_field(); ?>
<!-- Recaptcha Error -->
<?php if( $validation->getError('recaptcha_response') ) {?>
<div class="alert alert-danger">
<?= $validation->getError('recaptcha_response'); ?>
</div>
<?php }?>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="<?= old('name') ?>">
</div>
<!-- Error -->
<?php if( $validation->getError('name') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('name'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email" value="<?= old('email') ?>">
</div>
<!-- Error -->
<?php if( $validation->getError('email') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('email'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="subject">Subject:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="subject" placeholder="Enter Subject" name="subject" value="<?= old('subject') ?>" >
</div>
<!-- Error -->
<?php if( $validation->getError('subject') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('subject'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="message">Message:</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message"><?= old('message') ?></textarea>
</div>
<!-- Error -->
<?php if( $validation->getError('message') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('message'); ?>
</div>
<?php }?>
</div>
<div class="form-group ">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" id="recaptcha_response" name="recaptcha_response" value="">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using this you can protect your website without forcing the user to verify whether it is human or a bot.
You can also view this tutorial if you want to know Google reCAPTCHA v2 implementation in CodeIgniter 4.
If you found this tutorial helpful then don't forget to share.
Original article source at: https://makitweb.com/
1619247660
The liquid-cooled Tensor Processing Units, built to slot into server racks, can deliver up to 100 petaflops of compute.
The liquid-cooled Tensor Processing Units, built to slot into server racks, can deliver up to 100 petaflops of compute.
As the world is gearing towards more automation and AI, the need for quantum computing has also grown exponentially. Quantum computing lies at the intersection of quantum physics and high-end computer technology, and in more than one way, hold the key to our AI-driven future.
Quantum computing requires state-of-the-art tools to perform high-end computing. This is where TPUs come in handy. TPUs or Tensor Processing Units are custom-built ASICs (Application Specific Integrated Circuits) to execute machine learning tasks efficiently. TPUs are specific hardware developed by Google for neural network machine learning, specially customised to Google’s Machine Learning software, Tensorflow.
The liquid-cooled Tensor Processing units, built to slot into server racks, can deliver up to 100 petaflops of compute. It powers Google products like Google Search, Gmail, Google Photos and Google Cloud AI APIs.
#opinions #alphabet #asics #floq #google #google alphabet #google quantum computing #google tensorflow #google tensorflow quantum #google tpu #google tpus #machine learning #quantum computer #quantum computing #quantum computing programming #quantum leap #sandbox #secret development #tensorflow #tpu #tpus
1598923425
It’s always a good practice to prevent malicious software from engaging in abusive activities on your web application. The most popular tool to achieve that is Google’s reCAPTCHA. At the current state, it supports v2 and v3. In this article, we will focus on v3, as it requires less interaction with users and enables analytics.
recaptcha-endpoints
, inside your GOPATH
where all of our code will liveAfter registering your website, a new API key and secret pair will be generated. To make reCAPTCHA work, it requires changes on both frontend and backend services of your web application. We will only demonstrate on how to use it on the backend service, as Google’s documentation is pretty straight forward regarding the challenge placement on the frontend.
We will implement a simple server with a single endpoint to handle the login of users, given an email and password, protected with Google reCAPTCHA.
The way to verify a reCAPTCHA token is to make a POST
request on [https://www.google.com/recaptcha/api/siteverify](https://www.google.com/recaptcha/api/siteverify)
followed by the secret and the response token as URL parameters. Then evaluate the response to find out if the challenge was successful. Source code is about to follow.
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"os"
"time"
)
const siteVerifyURL = "https://www.google.com/recaptcha/api/siteverify"
type LoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
RecaptchaResponse string `json:"g-recaptcha-response"`
}
type SiteVerifyResponse struct {
Success bool `json:"success"`
Score float64 `json:"score"`
Action string `json:"action"`
ChallengeTS time.Time `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
func main() {
// Get recaptcha secret from env variable.
secret := os.Getenv("RECAPTCHA_SECRET")
// Define endpoint to handle login.
http.HandleFunc("/login", Login(secret))
log.Println("Server starting at port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func Login(secret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Decode request body.
var body LoginRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// Check and verify the recaptcha response token.
if err := CheckRecaptcha(secret, body.RecaptchaResponse); err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Check login credentials.
// ....
w.WriteHeader(http.StatusOK)
}
}
func CheckRecaptcha(secret, response string) error {
req, err := http.NewRequest(http.MethodPost, siteVerifyURL, nil)
if err != nil {
return err
}
// Add necessary request parameters.
q := req.URL.Query()
q.Add("secret", secret)
q.Add("response", response)
req.URL.RawQuery = q.Encode()
// Make request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Decode response.
var body SiteVerifyResponse
if err = json.NewDecoder(resp.Body).Decode(&body); err != nil {
return err
}
// Check recaptcha verification success.
if !body.Success {
return errors.New("unsuccessful recaptcha verify request")
}
// Check response score.
if body.Score < 0.5 {
return errors.New("lower received score than expected")
}
// Check response action.
if body.Action != "login" {
return errors.New("mismatched recaptcha action")
}
return nil
}
Let’s dive into it step by step
LoginRequest
struct that contains the user email and password to validate credentials, plus an extra field for reCAPTCHA token.SiteVerifyResponse
struct to decode the response from Google reCAPTCHA API.main
function to define the login endpoint handler, passing the reCAPTCHA secret as argument.Login
function that operates as handler where at first decodes the request body. Then checks and verifies the reCAPTCHA token calling the CheckRecaptcha
function and finally validate the provided credentials.CheckRecaptcha
function that does all the work regarding reCAPTCHA verification. Accepts the secret and response token as arguments, constructs the proper POST
request and makes it. Decode the response into the SiteVerifyResponse
struct and checks if the verification was successful, compares the received score against a provided minimum (0.5) and also checks the action name (login)You can set custom action names for any operation on your website, by setting the
_data-action_
attribute. In this way you can have access to a detailed break down of data in admin console and can apply different business logic for each action (e.g. 2FA authentication for login with low scores).
The above solution does the work, although it doesn’t scale while your web server is growing. It requires code duplication, generic code inside handlers and an extra field inside each struct, which used to decode requests body.
To avoid all that, we can implement a middleware to handle all the reCAPTCHA verification and apply to any endpoint is required. The previous code now becomes.
package main
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
const siteVerifyURL = "https://www.google.com/recaptcha/api/siteverify"
type LoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
type SiteVerifyResponse struct {
Success bool `json:"success"`
Score float64 `json:"score"`
Action string `json:"action"`
ChallengeTS time.Time `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
type SiteVerifyRequest struct {
RecaptchaResponse string `json:"g-recaptcha-response"`
}
func main() {
// Get recaptcha secret from env variable.
secret := os.Getenv("RECAPTCHA_SECRET")
// Define endpoint to handle login.
http.Handle("/login", RecaptchaMiddleware(secret)(Login()))
log.Println("Server starting at port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func Login() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Decode request body.
var body LoginRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// Check login credentials.
// ...
w.WriteHeader(http.StatusOK)
}
}
func CheckRecaptcha(secret, response string) error {
req, err := http.NewRequest(http.MethodPost, siteVerifyURL, nil)
if err != nil {
return err
}
// Add necessary request parameters.
q := req.URL.Query()
q.Add("secret", secret)
q.Add("response", response)
req.URL.RawQuery = q.Encode()
// Make request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Decode response.
var body SiteVerifyResponse
if err = json.NewDecoder(resp.Body).Decode(&body); err != nil {
return err
}
// Check recaptcha verification success.
if !body.Success {
return errors.New("unsuccessful recaptcha verify request")
}
// Check response score.
if body.Score < 0.5 {
return errors.New("lower received score than expected")
}
// Check response action.
if body.Action != "login" {
return errors.New("mismatched recaptcha action")
}
return nil
}
func RecaptchaMiddleware(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the reCaptcha response token from default request body field 'g-recaptcha-response'.
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Unmarshal body into struct.
var body SiteVerifyRequest
if err := json.Unmarshal(bodyBytes, &body); err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Restore request body to read more than once.
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// Check and verify the recaptcha response token.
if err := CheckRecaptcha(secret, body.RecaptchaResponse); err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
We will mention the changes against the first version of our code.
RecaptchaResponse
field has been removed from the LoginRequest
struct as is no longer need it.SiteVerifyRequest
has been introduced and will be used in middleware function to retrieve the reCAPTCHA token from request body.Login
handler function is now wrapped by RecaptchaMiddleware
.RecaptchaMiddleware
that accepts a secret has been created, that operates as middleware. Contains all the code regarding Google’s reCAPTCHA verification. Reads and decodes the request body into SiteVerityRequest
struct, then checks and verifies the reCAPTCHA at the same way as before.io.ReadCloser
type that can be read only once. For that reason we have to restore it, to be able to use it again in any following handler.That’s all the differences regarding the first version of our solution. In this way the code it’s a lot cleaner, handlers only contain the business logic that have been created for and the Google’s reCAPTCHA verification happens to a single place, inside the middleware.
I have implemented an open source package that handles Google’s reCAPTCHA verification that supports both v2 and v3. An out of the box middleware is also included. You can find it on GitHub.
#google-recaptcha #go #google #recaptcha #golang
1609258246
reCAPTCHA is a service that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.
reCAPTCHA v3 helps you detect abusive traffic on your website without user interaction. Instead of showing a CAPTCHA challenge, reCAPTCHA v3 returns a score so you can choose the most appropriate action for your website.
reCAPTCHA v3 scores are between 0–1.
reCAPTCHA v2 (“I’m not a robot” Checkbox) requires the user to click a checkbox indicating the user is not a robot. This will either pass the user immediately (with No CAPTCHA) or challenge them to validate whether or not they are human.
If you are looking a solution to integrate combined Google reCAPTCHA v2 & v3 to your website that is builded with .Net & C#, look at that → https://techtolia.com/Recaptcha/
With integrating the module to your ASP.NET web forms (such as login), check if the user is human or bot with combined of Google reCAPTCHA v2 & v3.
The module first verifies requests with reCAPTCHA v3 with a score. If the score is not higher than the pass score, module makes visible reCAPTCHA v2 with the “I’m not a robot” tickbox. If the user is verified with reCAPTCHA v2, score is going to be 1 (highest score) and Required Field Validator return true.
https://techtolia.medium.com/what-is-recaptcha-recaptcha-v2-v3-in-asp-net-e0efbce3128a
#recaptcha #asp.net #dotnet #csharp #google-recaptcha #captcha