当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

laravel-honeypot

Preventing spam submitted through forms
授权协议 MIT License
开发语言 PHP
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 寿翰飞
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Preventing spam submitted through forms

When adding a form to a public site, there's a risk that spam bots will try to submit it with fake values. Luckily, the majority of these bots are pretty dumb. You can thwart most of them by adding an invisible field to your form that should never contain a value when submitted. Such a field is called a honeypot. These spam bots will just fill all fields, including the honeypot.

When a submission comes in with a filled honeypot field, this package will discard that request.On top of that this package also checks how long it took to submit the form. This is done using a timestamp in another invisible field. If the form was submitted in a ridiculously short time, the anti spam will also be triggered.

After installing this package, all you need to do is to add the x-honeypot Blade component to your form.

<form method="POST">
    <x-honeypot />
    <input name="myField" type="text">
</form>

The package also supports manually passing the necessary values to your view layer, so you can easily add honeypot fields to your Inertia powered app.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Video tutorial

In this video, which is part of the Mailcoach video course, you can see how the package can be installed and used.

Installation

You can install the package via composer:

composer require spatie/laravel-honeypot

Optionally, you can publish the config file of the package.

php artisan vendor:publish --provider="Spatie\Honeypot\HoneypotServiceProvider" --tag=honeypot-config

This is the content of the config file that will be published at config/honeypot.php:

use Spatie\Honeypot\SpamResponder\BlankPageResponder;

return [
    /*
     * Here you can specify name of the honeypot field. Any requests that submit a non-empty
     * value for this name will be discarded. Make sure this name does not
     * collide with a form field that is actually used.
     */
    'name_field_name' => env('HONEYPOT_NAME', 'my_name'),

    /*
     * When this is activated there will be a random string added
     * to the name_field_name. This improves the
     * protection against bots.
     */
    'randomize_name_field_name' => env('HONEYPOT_RANDOMIZE', true),

    /*
     * This field contains the name of a form field that will be used to verify
     * if the form wasn't submitted too quickly. Make sure this name does not
     * collide with a form field that is actually used.
     */
    'valid_from_field_name' => env('HONEYPOT_VALID_FROM', 'valid_from'),

    /*
     * If the form is submitted faster than this amount of seconds
     * the form submission will be considered invalid.
     */
    'amount_of_seconds' => env('HONEYPOT_SECONDS', 1),

    /*
     * This class is responsible for sending a response to requests that
     * are detected as being spammy. By default a blank page is shown.
     *
     * A valid responder is any class that implements
     * `Spatie\Honeypot\SpamResponder\SpamResponder`
     */
    'respond_to_spam_with' => BlankPageResponder::class,

    /*
     * When activated, requests will be checked if honeypot fields are missing,
     * if so the request will be stamped as spam. Be careful! When using the
     * global middleware be sure to add honeypot fields to each form.
     */
    'honeypot_fields_required_for_all_forms' => false,

    /*
     * This switch determines if the honeypot protection should be activated.
     */
    'enabled' => env('HONEYPOT_ENABLED', true),
];

Usage

First, you must add the x-honeypot Blade component to any form you wish to protect.

<form method="POST" action="{{ route('contactForm.submit') }}")>
    <x-honeypot />
    <input name="myField" type="text">
</form>

Alternatively, you can use the @honeypot Blade directive:

<form method="POST" action="{{ route('contactForm.submit') }}")>
    @honeypot
    <input name="myField" type="text">
</form>

Using either the Blade component or directive will add two fields: my_name and my_time (you can change the names in the config file).

Next, you must use the Spatie\Honeypot\ProtectAgainstSpam middleware in the route that handles the form submission. This middleware will intercept any request that submits a non empty value for the key named my_name. It will also intercept the request if it is submitted faster than the encrypted timestamp that the package generated in my_time.

use App\Http\Controllers\ContactFormSubmissionController;
use Spatie\Honeypot\ProtectAgainstSpam;

Route::post('contact', [ContactFormSubmissionController::class, 'create'])->middleware(ProtectAgainstSpam::class);

If you want to integrate the Spatie\Honeypot\ProtectAgainstSpam middleware with Laravel's built in authentication routes, wrap the Auth::routes(); declaration with the appropriate middleware group (make sure to add the @honeypot directive to the authentication forms).

use Spatie\Honeypot\ProtectAgainstSpam;

Route::middleware(ProtectAgainstSpam::class)->group(function() {
    Auth::routes();
});

If your app has a lot of forms handled by many different controllers, you could opt to register it as global middleware.

// inside app\Http\Kernel.php

protected $middleware = [
   // ...
   \Spatie\Honeypot\ProtectAgainstSpam::class,
];

Usage in Inertia

When using Inertia you must manually pass the values used in the honeypot fields. Here's an example:

// in a controller
public function create(\Spatie\Honeypot\Honeypot $honeypot) 
{
    return inertia('contactform.show', [
        'honeypot' => $honeypot,
    ]);
}

Your front-end will get an honeypot object with these keys: enabled, nameFieldName, validFromFieldName, encryptedValidFrom.

Here's an example how these values could be rendered using Vue:

<div v-if="honeypot.enabled" :name="`${honeypot.nameFieldName}_wrap`" style="display:none;">
    <input type="text" v-model="form[honeypot.nameFieldName]" :name="honeypot.nameFieldName" :id="honeypot.nameFieldName" />
    <input type="text" v-model="form[honeypot.validFromFieldName]" :name="honeypot.validFromFieldName" />
</div>

And then in your Vue component, add these values to your form data:

props: ['honeypot'],

data() {
    return {
        form: this.$inertia.form({
            [this.honeypot.nameFieldName]: '',
            [this.honeypot.validFromFieldName]: this.honeypot.encryptedValidFrom,
        }),
    }
}

Disabling in testing

By default, any protected form that is submitted in faster than 1 second will be marked as spammy. When running end to end tests, which should run as fast as possible, you probably don't want this.

To disable all honeypots in code, you can set the enabled config value to false.

config()->set('honeypot.enabled', false)

Customizing the response

When a spammy submission is detected, the package will show a blank page by default. You can customize this behaviour by writing your own SpamResponse and specifying its fully qualified class name in the respond_to_spam_with key of the honeypot config file.

A valid SpamResponse is any class that implements the Spatie\Honeypot\SpamResponder\SpamResponder interface. This is what that interface looks like:

namespace Spatie\Honeypot\SpamResponder;

use Closure;
use Illuminate\Http\Request;

interface SpamResponder
{
    public function respond(Request $request, Closure $next);
}

Even though a spam responder's primary purpose is to respond to spammy requests, you could do other stuff there as well. You could for instance use the properties on $request to determine the source of the spam (maybe all requests come from the same IP) and put some logic to block that source altogether.

If the package wrongly determined that the request is spammy, you can generate the default response by passing the $request to the $next closure, like you would in a middleware.

// in your spam responder
$regularResponse = $next($request)

Customizing the generated honeypot fields

To customize output generated, you can publish the honeypot view with:

php artisan vendor:publish --provider="Spatie\Honeypot\HoneypotServiceProvider" --tag=views

The view will be placed in resources/views/vendor/honeypot/honeypotFormFields.blade.php. This is the default content:

@if($enabled)
    <div id="{{ $nameFieldName }}_wrap" style="display:none;">
        <input name="{{ $nameFieldName }}" type="text" value="" id="{{ $nameFieldName }}">
        <input name="{{ $validFromFieldName }}" type="text" value="{{ $encryptedValidFrom }}">
    </div>
@endif

Events fired

Whenever spam is detected, the Spatie\Honeypot|Events\SpamDetectedEvent event is fired. It has the $request as a public property.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Alternatives

If you need stronger spam protection, consider using Google ReCaptcha or Akismet.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Credits

This package was inspired by the Honeypot package by Maksim Surguy.

License

The MIT License (MIT). Please see License File for more information.

 相关资料
  • Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr

  • 我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))

  • Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap

  • 简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer

  • 简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果

  • WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D

  • 百度编辑器 For Laravel 5 支持自定义路由, 默认前后台独立控制器,支持重写方法方便自己的业务逻辑处理,支持扩展图片助手(推荐使用Intervention\Image第三方包) 官网 NinJa911工作室. 疑问讨论 请在issue里new一个. 授权 此Laravel 扩展包基于MIT协议开源MIT license. 安装 1.Composer 安装 composer requir

  • laravel-admin是一个基于laravel的后台管理开发框架,能帮助你使用很少的时间和代码量开发出功能完备的管理后台,另外它作为一个三方包,可以和框架内其它项目并行开发,真正做到前后台开发分离。 功能: RBAC权限管理模块。 菜单管理,和权限系统结合。 模型数据表格,能快速构建数据表格,并支持多种模型关系。 模型表单以及30+种form元素组件,自动实现增、删、改功能。 支持本地和云存储