概要
CakePHP3 の AuthComponent は非推奨になり、 CakePHP4 では AuthenticationComponent を使うことになる。
認証スキップのやり方が変わったのでメモしておく。
CakePHP3 の場合
\Cake\Controller\Component\AuthComponent::allow
を使えば良い。
Controller の initialize で、認証不要のアクションを指定してあげればいい。
<?php public function initialize(): void { parent::initialize(); $this->loadComponent('Auth'); // index アクションは認証不要 $this->Auth->allow('index'); }
CakePHP4 の場合
\Authentication\Controller\Component\AuthenticationComponent::allowUnauthenticated
を使う。
AuthComponent では複数アクション指定の場合は配列、単独の場合は文字列で指定できたが、 AuthenticationComponent の場合は必ず配列で指定する必要がある。
<?php public function initialize(): void { parent::initialize(); $this->loadComponent('Authentication.Authentication'); // 必ず配列で指定する $this->Authentication->allowUnauthenticated(['index']); }
Controller 単位で認証不要にするには?
Cake3 (AuthComponent) の場合は、 allow の引数を指定しないことで全アクションを対象にできた。
<?php public function initialize(): void { parent::initialize(); $this->loadComponent('Auth'); // Controller 内すべてのアクションで認証不要になる $this->Auth->allow(); }
ただし Cake4 (AuthenticationComponent) では設定でチェックを無効化する形になる。
<?php public function initialize(): void { parent::initialize(); $this->loadComponent('Authentication.Authentication', [ // requireIdentity で無効化する 'requireIdentity' => false, ]); }
実際に AuthenticationComponent を利用する際は AppController など基底クラスで load することになると思うので、各コントローラで設定を切り替えてやればよい。
<?php public function initialize(): void { parent::initialize(); // 認証不要 $this->Authentication->setConfig('requireIdentity', false); }