PHP code example of rrd108 / api-token-authenticator

1. Go to this page and download the library: Download rrd108/api-token-authenticator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rrd108 / api-token-authenticator example snippets



return [
  'ApiTokenAuthenticator' => [
    'header' => 'Authorization',
  ]
];


return [
  'ApiTokenAuthenticator' => [
    'header' => 'Authorization',
    'prefix' => 'Bearer',
  ]
];

return [
  // other plugins
  'ApiTokenAuthenticator' => [],
];

public function initialize(): void
{
  parent::initialize();
  $this->loadComponent('Authentication.Authentication');
}

use Cake\View\JsonView;

public function viewClasses(): array
{
  return [JsonView::class];
}

use Authentication\PasswordHasher\DefaultPasswordHasher;
protected function _setPassword(string $password)
{
  $hasher = new DefaultPasswordHasher();
  return $hasher->hash($password);
}

$routes->scope('/', function (RouteBuilder $builder): void {
  // other routes
  $builder->setExtensions(['json']);
  $builder->resources('Users');

  $builder->fallbacks();
});

// for example in UsersController.php
public function index()
{
  $query = $this->Users->find();
  $users = $this->paginate($query);

  $this->set(compact('users'));
  $this->viewBuilder()->setOption('serialize', ['users']);
}

public function login()
{
  $result = $this->Authentication->getResult();
  if ($result->isValid()) {
    $user = $this->Authentication->getIdentity()->getOriginalData();
    $this->set(compact('user'));
    $this->viewBuilder()->setOption('serialize', ['user']);
  }
}

public function beforeFilter(\Cake\Event\EventInterface $event)
{
  parent::beforeFilter($event);
  $this->Authentication->allowUnauthenticated(['login']);
}

public function login()
{
  $result = $this->Authentication->getResult();
  if ($result->isValid()) {
    $user = $this->Authentication->getIdentity()->getOriginalData();
    $user->token = $this->generateToken();
    $user = $this->Users->save($user);
    $user = $this->Users->get($user->id);

    $this->set(compact('user'));
    $this->viewBuilder()->setOption('serialize', ['user']);
  }
  // if login failed you can throw an exception, suggested: rrd108/cakephp-json-api-exception
}

private function generateToken(int $length = 36)
{
  $random = base64_encode(Security::randomBytes($length));
  $cleaned = preg_replace('/[^A-Za-z0-9]/', '', $random);
  return substr($cleaned, 0, $length);
}

protected $_accessible = [
  'email' => true,
  // your other fields here
  'token' => true,
  'token_expiration' => true,
];

$validator
  ->dateTime('token_expiration')
  ->allowEmptyDateTime('token_expiration');

public function login()
{
  $result = $this->Authentication->getResult();
  if ($result->isValid()) {
    $user = $this->Authentication->getIdentity()->getOriginalData();
    list($user->token, $user->token_expiration) = $this->generateToken();
    $user = $this->Users->save($user);

    $this->set(compact('user'));
    $this->viewBuilder()->setOption('serialize', ['user']);

    // delete all expired tokens
    $this->Users->updateAll(
      ['token' => null, 'token_expiration' => null],
      ['token_expiration <' => Chronos::now()]
    );
  }
}

private function generateToken(int $length = 36, string $expiration = '+6 hours')
{
  $random = base64_encode(Security::randomBytes($length));
  $cleaned = preg_replace('/[^A-Za-z0-9]/', '', $random);
  return [$cleaned, strtotime($expiration)];
}

// in UsersController.php
public function beforeFilter(\Cake\Event\EventInterface $event)
{
  parent::beforeFilter($event);
  $this->Authentication->allowUnauthenticated(['login', 'index']);
}