CakePHP4のメモ
![]() |
13 |
289 views
CakePHP4では、Authenticationプラグインを使用して簡単にユーザー認証機能を実装できます。このプラグインは、セキュリティが強化された認証を提供し、ユーザーのログイン、ログアウト、登録機能などを構築するのに便利です。この記事では、Authenticationプラグインの導入から、ユーザー認証機能を実装するまでの手順を解説します。
まず、CakePHP4のAuthenticationプラグインをインストールします。プロジェクトのルートディレクトリで以下のコマンドを実行してください。
composer require cakephp/authentication
インストールが完了したら、プラグインを読み込むためにsrc/Application.php
を編集し、プラグインのロード設定を追加します。
public function bootstrap(): void
{
parent::bootstrap();
$this->addPlugin('Authentication');
}
認証対象となるユーザー情報を保存するためのusers
テーブルを作成し、ユーザー名とパスワードのフィールドを用意します。
MySQLで以下のコマンドを実行し、users
テーブルを作成します。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL,
created DATETIME,
modified DATETIME
);
次に、CakePHPのbake
コマンドを使用してUsers
モデルを生成します。
bin/cake bake model Users
これにより、src/Model/Entity/User.php
とsrc/Model/Table/UsersTable.php
が生成されます。
パスワードはハッシュ化して保存します。UsersTable
に以下のコードを追加し、パスワードのハッシュ化を自動化します。
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Event\EventInterface;
use ArrayObject;
use Authentication\PasswordHasher\DefaultPasswordHasher;
class UsersTable extends Table
{
public function initialize(array $config): void
{
parent::initialize($config);
$this->addBehavior('Timestamp');
}
public function beforeSave(EventInterface $event, $entity, ArrayObject $options)
{
if ($entity->isNew() && $entity->get('password')) {
$hasher = new DefaultPasswordHasher();
$entity->set('password', $hasher->hash($entity->get('password')));
}
}
}
beforeSave
メソッドで、新規ユーザーのパスワードが自動的にハッシュ化されるように設定しています。
ユーザー登録のためのフォームと、登録データを保存する処理を追加します。
templates/Users/add.php
に、以下のようにユーザー登録用のフォームを作成します。
<h1>ユーザー登録</h1>
<div class="users form">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('ユーザー情報を入力してください') ?></legend>
<?= $this->Form->control('username') ?>
<?= $this->Form->control('password', ['type' => 'password']) ?>
</fieldset>
<?= $this->Form->button(__('登録')) ?>
<?= $this->Form->end() ?>
</div>
UsersController.php
に、add
アクションを追加し、ユーザー登録処理を記述します。
public function add()
{
$user = $this->Users->newEmptyEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('ユーザー登録が完了しました。'));
return $this->redirect(['action' => 'login']);
}
$this->Flash->error(__('登録に失敗しました。もう一度お試しください。'));
}
$this->set(compact('user'));
}
認証プラグインのミドルウェアを設定します。src/Application.php
を編集し、ミドルウェアにAuthenticationプラグインを追加します。
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$middlewareQueue
->add(new AuthenticationMiddleware($this));
return $middlewareQueue;
}
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationService
{
$service = new AuthenticationService();
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'fields' => ['username' => 'username', 'password' => 'password'],
'loginUrl' => '/users/login'
]);
$service->loadIdentifier('Authentication.Password', [
'fields' => ['username' => 'username', 'password' => 'password']
]);
return $service;
}
ユーザーがログインできるように、UsersController
にlogin
アクションを追加します。
templates/Users/login.php
にログインフォームを作成します。
<h1>ログイン</h1>
<div class="users form">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('ユーザー名とパスワードを入力してください') ?></legend>
<?= $this->Form->control('username') ?>
<?= $this->Form->control('password', ['type' => 'password']) ?>
</fieldset>
<?= $this->Form->button(__('ログイン')) ?>
<?= $this->Form->end() ?>
</div>
UsersController.php
にログイン処理を記述します。
use Authentication\Authenticator\Result;
public function login()
{
$result = $this->Authentication->getResult();
if ($this->request->is('post') && $result->isValid()) {
$redirect = $this->request->getQuery('redirect', [
'controller' => 'Pages',
'action' => 'display',
'home'
]);
return $this->redirect($redirect);
}
if ($result && !$result->isValid()) {
$this->Flash->error(__('ユーザー名またはパスワードが正しくありません。'));
}
}
getResult()
を使って、認証結果をチェックします。最後に、ログアウト機能を実装します。UsersController
にlogout
アクションを追加します。
public function logout()
{
$this->request->getSession()->destroy();
$this->Flash->success(__('ログアウトしました。'));
return $this->redirect(['action' => 'login']);
}
認証されたユーザーのみがアクセスできるよう、アクションにアクセス制限を設定します。initialize
メソッドでrequireAuth
を有効にし、未ログイン時のアクセス制限を追加します。
public function initialize(): void
{
parent::initialize();
$this->Authentication->addUnauthenticatedActions(['login', 'add']);
}
CakePHP4のAuthenticationプラグインを使うことで、セキュアで便利なユーザー認証機能を簡単に実装できます。今回の手順に従えば、ユーザーの登録、ログイン、ログアウト機能が完成し、アクセス制限も適切に管理できます。今後は、さらに詳細なユーザー管理や、権限の設定に挑戦してみましょう。
Page 24 of 34.
1.php_xdebug-3.0.4-8.0-vs16-x86_64.dll
すぺぺぺ
本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。
https://www.osumoi-stdio.com/novel/