Laravel 5.0 Auth CAPTCHA Example

Laravel Auth CAPTCHA Example demonstrates how to integrate BotDetect PHP Captcha into login, register and reset password forms in a scenario where Laravel Auth is used to authenticate users to your application.

First Time Here?

Check the BotDetect Laravel 5.0 Captcha Quickstart for key integration steps.

Alongside the Captcha image, the user is provided with an input field to retype the displayed characters. Depending on if the Captcha code entered matches the displayed one or not, a message stating the validation result is shown on the form.

The simple code showing the message in this example would of course be replaced with useful form processing code in a real world scenario.

The default in Laravel 5.0 ships an example to authenticate users that is used Laravel Auth, but no captcha image is created. Here's what we started:

First, we need to configure database connection with entering connection details into the /config/database.php file.

Next, we need to create users and password_resets tables -- using Migrations.

To create that tables, run the following command in your application's root directory:

Files for this example are:

The files are available for download as a part of the BotDetect Captcha Laravel integration package.

Routing – /app/Http/routes.php

Route::controllers([
  'auth' => 'Auth\AuthController',
  'password' => 'Auth\PasswordController',
]);

In the code above we use the Implicit Controllers to define a single route which will handle every action in the AuthController and PasswordController.

Config – /config/captcha.php

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

return [
  // Captcha configuration for login page
  'LoginCaptcha' => [
    'UserInputID' => 'CaptchaCode',
    'CodeLength' => CaptchaRandomization::GetRandomCodeLength(4, 6),
    'ImageStyle' => [
      ImageStyle::Radar,
      ImageStyle::Collage,
      ImageStyle::Fingerprints,
    ],
  ],

  // Captcha configuration for register page
  'RegisterCaptcha' => [
    'UserInputID' => 'CaptchaCode',
    'CodeLength' => CaptchaRandomization::GetRandomCodeLength(4, 7),
    'CodeStyle' => CodeStyle::Alpha,
  ],

  // Captcha configuration for reset password page
  'ResetPasswordCaptcha' => [
    'UserInputID' => 'CaptchaCode',
    'CodeLength' => CaptchaRandomization::GetRandomCodeLength(3, 6),
    'CustomLightColor' => '#9966FF',
  ],

];

In order to use the Laravel CAPTCHA Package, we have declared Captcha configuration which will be used when showing Captcha image in login, register, and reset password views. Detailed description of this approach is available in a BotDetect Laravel 5.0 integration guide.

View – /resources/views/app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel Auth Example</title>
  <link href="{{ URL::asset('css/bootstrap.min.css') }}" type="text/css" rel="stylesheet">

  <!-- include the BotDetect layout stylesheet -->
  <link href="{{ captcha_layout_stylesheet_url() }}" type="text/css" rel="stylesheet">
</head>
<body>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle Navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Laravel Auth</a>
      </div>

      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li><a href="/">Home</a></li>
        </ul>

        <ul class="nav navbar-nav navbar-right">
          @if (Auth::guest())
            <li><a href="{{ URL::to('auth/login') }}">Login</a></li>
            <li><a href="{{ URL::to('auth/register') }}">Register</a></li>
          @else
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                {{ Auth::user()->name }} <span class="caret"></span>
              </a>
              <ul class="dropdown-menu" role="menu">
                <li><a href="{{ URL::to('auth/logout') }}">Logout</a></li>
              </ul>
            </li>
          @endif
        </ul>
      </div>
    </div>
  </nav>

  @yield('content')

  <!-- Scripts -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

The above code is defining a Blade Layout. The app view needs to add the required stylesheet of the library.

View – /resources/views/auth/login.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Login</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input.<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" action="{{ URL::to('auth/login') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">

            <div class="form-group">
              <label class="col-md-4 control-label">E-Mail Address</label>
              <div class="col-md-6">
                <input type="email" class="form-control" name="email" value="{{ old('email') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Show captcha image html-->
                {!! captcha_image_html('LoginCaptcha') !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                 <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" name="remember"> Remember Me
                  </label>
                </div>
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary" style="margin-right: 15px;">
                  Login
                </button>

                <a href="{{ URL::to('password/email') }}">Forgot Your Password?</a>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code is to display authentication in a view, we show Captcha image by calling captcha_image_html() helper function. It is required to pass a captcha configuration key defined in config/captcha.php file (i.e. LoginCaptcha). We have also added Captcha Code input field to view.

View – /resources/views/auth/register.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Register</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input.<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" action="{{ URL::to('auth/register') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">

            <div class="form-group">
              <label class="col-md-4 control-label">Name</label>
              <div class="col-md-6">
                <input type="text" class="form-control" name="name" value="{{ old('name') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">E-Mail Address</label>
              <div class="col-md-6">
                <input type="email" class="form-control" name="email" value="{{ old('email') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Confirm Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password_confirmation">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Show captcha image html-->
                {!! captcha_image_html('RegisterCaptcha') !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                  Register
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code is to display authentication in a view, we show Captcha image by calling captcha_image_html() helper function. It is required to pass a captcha configuration key defined in config/captcha.php file (i.e. RegisterCaptcha). We have also added Captcha Code input field to view.

View – /resources/views/auth/password.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Reset Password</div>
        <div class="panel-body">
          @if (session('status'))
            <div class="alert alert-success">
              {{ session('status') }}
            </div>
          @endif

          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input.<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" action="{{ URL::to('password/email') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">

            <div class="form-group">
              <label class="col-md-4 control-label">E-Mail Address</label>
              <div class="col-md-6">
                <input type="email" class="form-control" name="email" value="{{ old('email') }}">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Show captcha image html-->
                {!! captcha_image_html('ResetPasswordCaptcha') !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                  Send Password Reset Link
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code is to display authentication in a view, we show Captcha image by calling captcha_image_html() helper function. It is required to pass a captcha configuration key defined in config/captcha.php file (i.e. ResetPasswordCaptcha). We have also added Captcha Code input field to view.

Controller – /app/Http/Controllers/Auth/AuthController.php

<?php namespace App\Http\Controllers\Auth;

use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;

class AuthController extends Controller {

  /*
  |--------------------------------------------------------------------------
  | Registration & Login Controller
  |--------------------------------------------------------------------------
  |
  | This controller handles the registration of new users, as well as the
  | authentication of existing users. By default, this controller uses
  | a simple trait to add these behaviors. Why don't you explore it?
  |
  */

  use AuthenticatesAndRegistersUsers;

  /**
   * Create a new authentication controller instance.
   *
   * @param  \Illuminate\Contracts\Auth\Guard  $auth
   * @param  \Illuminate\Contracts\Auth\Registrar  $registrar
   * @return void
   */
  public function __construct(Guard $auth, Registrar $registrar)
  {
    $this->auth = $auth;
    $this->registrar = $registrar;

    $this->middleware('guest', ['except' => 'getLogout']);
  }

  public function postRegister(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'required|max:255',
      'email' => 'required|email|max:255|unique:users',
      'password' => 'required|confirmed|min:6',
      'CaptchaCode' => 'required|valid_captcha',
    ]);

    if ($validator->fails())
    {
      $this->throwValidationException(
        $request, $validator
      );
    }

    $this->auth->login($this->registrar->create($request->all()));

    return redirect($this->redirectPath());
  }

  public function postLogin(Request $request)
  {
    $this->validate($request, [
      'email' => 'required|email', 'password' => 'required',
      'CaptchaCode' => 'required|valid_captcha'
    ]);

    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials, $request->has('remember')))
    {
      return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
          ->withInput($request->only('email', 'remember'))
          ->withErrors([
            'email' => $this->getFailedLoginMessage(),
          ]);
  }

}

The Controller part of the example provides necessary helpers and data used by View, and adds the Captcha validation functionality as outlined in the BotDetect Laravel 5.0 integration guide.

The code above is that we are overridden the AuthenticatesAndRegistersUsers trait of the Laravel.

Method: postRegister()

On HTTP POST request (user submit), the postRegister() action executes and we validate user entered data using the Validation class and validate the user's Captcha code input by using the valid_captcha validation rule.

Method: postLogin()

On HTTP POST request (user submit), the postLogin() action executes and we check user's email and password using the Auth::attempt() and validate the user's Captcha code input by using the valid_captcha validation rule.

Controller – /app/Http/Controllers/Auth/PasswordController.php

<?php namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;

class PasswordController extends Controller {

  /*
  |--------------------------------------------------------------------------
  | Password Reset Controller
  |--------------------------------------------------------------------------
  |
  | This controller is responsible for handling password reset requests
  | and uses a simple trait to include this behavior. You're free to
  | explore this trait and override any methods you wish to tweak.
  |
  */

  use ResetsPasswords;

  /**
   * Create a new password controller instance.
   *
   * @param  \Illuminate\Contracts\Auth\Guard  $auth
   * @param  \Illuminate\Contracts\Auth\PasswordBroker  $passwords
   * @return void
   */
  public function __construct(Guard $auth, PasswordBroker $passwords)
  {
    $this->auth = $auth;
    $this->passwords = $passwords;

    $this->middleware('guest');
  }

  public function postEmail(Request $request)
  {
    $this->validate($request, [
      'email' => 'required|email',
      'CaptchaCode' => 'required|valid_captcha'
    ]);

    $response = $this->passwords->sendResetLink($request->only('email'), function($m)
    {
      $m->subject($this->getEmailSubject());
    });

    switch ($response)
    {
      case PasswordBroker::RESET_LINK_SENT:
        return redirect()->back()->with('status', trans($response));

      case PasswordBroker::INVALID_USER:
        return redirect()->back()->withErrors(['email' => trans($response)]);
    }
  }

}

The Controller part of the example provides necessary helpers and data used by View, and adds the Captcha validation functionality as outlined in the BotDetect Laravel 5.0 integration guide.

The code above is that we are overridden the ResetsPasswords trait of the Laravel.

On HTTP POST request (user submit), the postEmail() action executes and we validate user entered data using the Validation class and validate Captcha Code by using the valid_captcha validation rule.