Csrf tokens

Adding a csrf token will prevent csrf attacks.

Adding a token

Add an extra html input field inside the form to add a token. The type should be hidden, the name can be anything but the name of token suits. The token value can be generated by calling the token function method statically.

Use the developer tools inside your browser to check if the token actually is generated the correct way.

<input type="hidden" name="token" value="<?php core\Csrf::token(); ?>"/>    

Validating a token

Change the token value using the browser development inspecting tools to trigger an invalid token. After submitting the form, the token is invalid and should not pass the validation.

<?php

  namespace app\controllers;
  
  use core\Csrf;
  use validation\Rules;
                
  class ExampleController extends Controller {
                  
    public function example($request) {    
                        
      $rules = new Rules();

      if($rules->exampleRules($request['token'], Csrf::get())->validated() ) {
                  
        /**
        * Token is valid    
        *   
        */
                
      }      
    }  
  }      

Applying the csrf rule.


<?php
                
  namespace validation;
                
  use core\validation\Validate;
                
  class Rules {
                
    public $errors;
                 
    public function exampleRules($requestTokenValue, $tokenValue) {    
                
      $validation = new Validate();
                
      $validation->input(['token' => $requestTokenValue])->as('Token')->rules(['csrf' => $tokenValue]);

      $this->errors = $validation->errors;
      return $this;
    }
                
    public function validated() {    
                
      if(empty($this->errors) ) {
                
        return true;
      } 
    }       
  }