質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

MAMP

Mac 上で WordPress などの動的ページのサイトが作れるように環境を構築するフリーソフト

Q&A

0回答

1601閲覧

Cakephp4 ユーザー認証機能実装、認証が成功しない。

sawara29

総合スコア12

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

MAMP

Mac 上で WordPress などの動的ページのサイトが作れるように環境を構築するフリーソフト

0グッド

0クリップ

投稿2021/03/13 11:06

MAMP環境に、Cakephp4を下記のサイトを参考にして、勉強してます。リンク内容

Authenticationプラグインを実装して、http://localhost/caketest/admin/users/loginログイン画面から、
ユーザーネームとパスワードを入力しますが、

ユーザー名かパスワードが正しくありません。と表示されます。

データとしていれた、どの名前と、パスワードでもエラーなので、loginのメソッドが機能をしていないようです。loginメソッドを入れた、UsersController.php

declare(strict_types=1); namespace App\Controller\Admin; use App\Controller\Admin\AdminController; class UsersController extends AdminController { public function beforeFilter(\Cake\Event\EventInterface $event) { parent::beforeFilter($event); // 認証を必要としないログインアクションを構成し、 // 無限リダイレクトループの問題を防ぎます $this->Authentication->addUnauthenticatedActions(['login']); } public function index() { $users = $this->paginate($this->Users); $this->set(compact('users')); } public function view($id = null) { $user = $this->Users->get($id, [ 'contain' => [], ]); $this->set(compact('user')); } 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(__('The user has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The user could not be saved. Please, try again.')); } $this->set(compact('user')); } public function edit($id = null) { $user = $this->Users->get($id, [ 'contain' => [], ]); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The user could not be saved. Please, try again.')); } $this->set(compact('user')); } /** * Delete method * * @param string|null $id User id. * @return \Cake\Http\Response|null|void Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $user = $this->Users->get($id); if ($this->Users->delete($user)) { $this->Flash->success(__('The user has been deleted.')); } else { $this->Flash->error(__('The user could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } public function login() { $this->request->allowMethod(['get', 'post']); $result = $this->Authentication->getResult(); // POST, GET を問わず、ユーザーがログインしている場合はリダイレクトします if ($result->isValid()) { return $this->redirect('/admin'); } // ユーザーが submit 後、認証失敗した場合は、エラーを表示します if ($this->request->is('post') && !$result->isValid()) { $this->Flash->error('ユーザー名かパスワードが正しくありません。'); } } }

認証プラグインApplication.php

<?php declare(strict_types=1); namespace App; use Cake\Core\Configure; use Cake\Core\ContainerInterface; use Cake\Core\Exception\MissingPluginException; use Cake\Datasource\FactoryLocator; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Http\Middleware\BodyParserMiddleware; use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Http\MiddlewareQueue; use Cake\ORM\Locator\TableLocator; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; use Authentication\AuthenticationService; use Authentication\AuthenticationServiceInterface; use Authentication\AuthenticationServiceProviderInterface; use Authentication\Middleware\AuthenticationMiddleware; use Psr\Http\Message\ServerRequestInterface; class Application extends BaseApplication implements AuthenticationServiceProviderInterface { /** * Load all the application configuration and bootstrap logic. * * @return void */ public function bootstrap(): void { // Call parent to load bootstrap from files. parent::bootstrap(); if (PHP_SAPI === 'cli') { $this->bootstrapCli(); } else { FactoryLocator::add( 'Table', (new TableLocator())->allowFallbackClass(false) ); } /* * Only try to load DebugKit in development mode * Debug Kit should not be installed on a production system */ if (Configure::read('debug')) { $this->addPlugin('DebugKit'); } // Load more plugins here } **編集箇所** public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { $middlewareQueue // Catch any exceptions in the lower layers, // and make an error page/response ->add(new ErrorHandlerMiddleware(Configure::read('Error'))) // Handle plugin/theme assets like CakePHP normally does. ->add(new AssetMiddleware([ 'cacheTime' => Configure::read('Asset.cacheTime'), ])) // Add routing middleware. // If you have a large number of routes connected, turning on routes // caching in production could improve performance. For that when // creating the middleware instance specify the cache config name by // using it's second constructor argument: // `new RoutingMiddleware($this, '_cake_routes_')` ->add(new RoutingMiddleware($this)) // 認証機能 ->add(new AuthenticationMiddleware($this)) // Parse various types of encoded request bodies so that they are // available as array through $request->getData() // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware ->add(new BodyParserMiddleware()) // Cross Site Request Forgery (CSRF) Protection Middleware // https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware ->add(new CsrfProtectionMiddleware(['httponly' => true])); return $middlewareQueue; } public function services(ContainerInterface $container): void { } public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface { $authenticationService = new AuthenticationService([ 'unauthenticatedRedirect' => '/admin/users/login', 'queryParam' => 'redirect', ]); // identifiers を読み込み、username と password のフィールドを確認します $authenticationService->loadIdentifier('Authentication.Password', [ 'fields' => [ 'username' => 'username', 'password' => 'password', ] ]); // authenticatorsをロードしたら, 最初にセッションが必要です $authenticationService->loadAuthenticator('Authentication.Session'); // 入力した username と password をチェックする為のフォームデータを設定します $authenticationService->loadAuthenticator('Authentication.Form', [ 'fields' => [ 'username' => 'username', 'password' => 'password', ], 'loginUrl' => '/admin/users/login', ]); return $authenticationService; } /** * Bootstrapping for CLI application. * * That is when running commands. * * @return void */ protected function bootstrapCli(): void { try { $this->addPlugin('Bake'); } catch (MissingPluginException $e) { // Do not halt if the plugin is missing } $this->addPlugin('Migrations'); // Load more plugins here } }

入力したUsersSeed.php

<?php declare(strict_types=1); use Migrations\AbstractSeed; use Authentication\PasswordHasher\DefaultPasswordHasher; /** * Users seed. */ class UsersSeed extends AbstractSeed { > 編集箇所 public function run() { $data = [ [ 'username' => 'admin', 'password' => $this->_setPassword('admin'), 'created' => '2021-03-08 09:10:00', 'modified' => '2021-03-08 09:10:00' ], [ 'username' => 'yamada', 'password' => $this->_setPassword('yamada'), 'created' => '2021-03-08 09:10:00', 'modified' => '2021-03-08 09:10:00' ] ]; $table = $this->table('users'); $table->insert($data)->save(); } protected function _setPassword(string $password) : ?string { if (strlen($password) > 0) { return (new DefaultPasswordHasher())->hash($password); } } }

データベースには、入力されてます。
初心者で、どうしてよいか、止まってます。どなたか、良きアドバイスをお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問