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/ */
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,
];
// in UsersController.php
public function beforeFilter(\Cake\Event\EventInterface $event)
{
parent::beforeFilter($event);
$this->Authentication->allowUnauthenticated(['login', 'index']);
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.