Windowsで始めるCakePHP4

CakePHP4のメモ

296 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 12 of 17.

前のページ 次のページ



[添付ファイル]

1.php_xdebug-3.0.4-8.0-vs16-x86_64.dll  


お問い合わせ

プロフィール

マッスル

自己紹介

本サイトの作成者。
趣味:プログラム/水耕栽培/仮想通貨/激辛好き
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
仮想通貨はNEMが好き。
水耕栽培は激辛好きが高じて、キャロライナ・リーパーの栽培にチャレンジ中。

サイト/ブログ

https://www.osumoi-stdio.com/pyarticle/

ツイッター

@darkimpact0626