CakePHP4のメモ
![]() |
13 |
681 views
CakePHP 4で簡単に認証を行う方法として、cakephp/authenticationというプラグインを利用するのが一般的です。
認証方式はシンプルな認証と認可のアプリケーションに従って実装します。
ただし、上記手順のsrc/Application.phpのコードには誤りがあります。
unauthenticatedRedirectとloginUrlに指定するURLを、Routerを使って指定するように変更します。
unauthenticatedRedirectは6行目、loginUrlは29行目にあります。
use Cake\Routing\Router;
…
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => Router::url([
'controller' => 'Users',
'action' => 'login'
]),
'queryParam' => 'redirect',
]);
// 識別子をロードして、電子メールとパスワードのフィールドを確認します
$authenticationService->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'email',
'password' => 'password',
]
]);
// 認証子をロードするには、最初にセッションを実行する必要があります
$authenticationService->loadAuthenticator('Authentication.Session');
// メールとパスワードを選択するためのフォームデータチェックの設定
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'email',
'password' => 'password',
],
'loginUrl' => Router::url([
'plugin' => null,
'prefix' => null,
'controller' => 'Users',
'action' => 'login'
])
]);
return $authenticationService;
}
}
【ポイント】
テスト時のURLにhttp://localhost/users/login/を指定した場合も認証エラーになります。
原因は末尾の/(スラッシュ)です。
http://localhost/users/loginを入力しましょう。
Page 13 of 34.
1.php_xdebug-3.0.4-8.0-vs16-x86_64.dll
すぺぺぺ
本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。
https://www.osumoi-stdio.com/novel/