[yii2] Show captcha after failed login attempt

If you have a login page that can be reached over the internet, at some point that page will be attacked. The reason for this is that it is very easy for an attacker to do so.

Brute force attacks are attempts to gain access to an account by guessing the username and password used. Brute force attack is actually an old technique in cybercrime. However, it is still widely used because it is considered still effective.

One way to secure a website from brute force attacks is to use a captcha (Completely Automated Public Test to Tell Computers and Humans Apart). In this tutorial, we will learn to activate captcha after the user fails to login. For how to create a captcha you can read on [yii2]Create a Login Form with Captcha.

Steps to activate captcha after user fails to login:

1. Add captcha fields and validation rules to models/LoginForm.php

class LoginForm extends Model
{
    .............
    .............
    public $verifyCode;
    .............
  
    public function rules()
    {
        return [
            .............
            .............
  
            ['verifyCode', 'required', 'when'=>function(){return $this->loginFailed;}],
            ['verifyCode', 'captcha', 'when'=>function(){return $this->loginFailed;}],
              
            .............
            .............
        ];
    }
 
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            .............
            if (!$user || !$user->validatePassword($this->password)) {
 
                Yii::$app->session->set('_loginAttempts', Yii::$app->session->get('_loginAttempts', 0)+1);
 
                .............
            }
        }
    }   
     
    //Check number login failed
    public function getLoginFailed()
    {
        return Yii::$app->session->get('_loginAttempts', 0) > 3;
    }
     
    .............
    .............   
}

2. Add widgets to views/site/login.php

.............
.............
 
<div class="site-login">
    .............
    .............
 
    <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
 
                .............
                .............
 
                <?php
                if($model->loginFailed){
                    echo $form->field($model, 'verifyCode')->widget(\yii\captcha\Captcha::class);
                }
                ?>
 
                .............
                .............
     
            <?php ActiveForm::end(); ?>
        </div>
    </div>
</div>

3. Add action to the controller/SiteController.php

For captchas to work, you’ll need to add an action captcha to controllers/SiteController.php. Maybe the action already exists because the standard Yii2 app template adds it automatically.

.............
.............
  
class SiteController extends Controller
{
    .............
    .............
      
    public function actions()
    {
        return [
            .............
            .............
              
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
            ],
            .............
            .............
        ];
    }
      
    .............
    .............   
}

Latest Articles