я не могу пройти проверку подлинности в Cakephp 4, ошибка 500

#php #authentication #cakephp #cakephp-4.x

Вопрос:

Я пытаюсь выполнить аутентификацию через КЛУБ пользователей, но получаю сообщение об ошибке 500 внутреннего сервера, я не понимаю почему, это происходит со мной только при использовании аутентификации. может быть, это ошибка конфигурации?

ошибка консоли firefox — ПОЛУЧИТЬ http://localhost/learnwithus/users 500 Внутренняя ошибка Сервера

Error.log

     Request URL: /Users/login
Client IP: 192.168.152.1


2021-10-18 20:59:57 Error: [Exception] The request object does not contain the required `authentication` attribute in /opt/lampp/htdocs/learnwithus/vendor/cakephp/authentication/src/Controller/Component/AuthenticationComponent.php on line 142
Stack Trace:
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/authentication/src/Controller/Component/AuthenticationComponent.php:93
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Event/EventManager.php:309
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Event/EventManager.php:286
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Event/EventDispatcherTrait.php:92
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Controller/Controller.php:575
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php:96
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/BaseApplication.php:313
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:77
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Middleware/CsrfProtectionMiddleware.php:159
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Middleware/BodyParserMiddleware.php:159
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php:161
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Routing/Middleware/AssetMiddleware.php:68
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php:126
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/debug_kit/src/Middleware/DebugKitMiddleware.php:60
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Runner.php:58
- /opt/lampp/htdocs/learnwithus/vendor/cakephp/cakephp/src/Http/Server.php:90
- /opt/lampp/htdocs/learnwithus/webroot/index.php:40
 

Мой контроллер

   <?php
    
    class UsersController extends AppController
    {
    
        public function beforeFilter(CakeEventEventInterface $event) {
            parent::beforeFilter($event);
            $this->Authentication->addUnauthenticatedActions(['login']);
        }
    
        public function login() {
            $this->request->allowMethod(['get', 'post']);
            $result = $this->Authentication->getResult();
            if ($result->isValid()) {
                $redirect = $this->request->getQuery('redirect', [
                    'controller' => 'Users',
                    'action' => 'index',
                ]);
    
                return $this->redirect($redirect);
            }
            if ($this->request->is('post') amp;amp; !$result->isValid()) {
                $this->Flash->error(__('Invalid username or password'));
            }
        }
    
        public function logout() {
            $result = $this->Authentication->getResult();
            if ($result->isValid()) {
                $this->Authentication->logout();
                return $this->redirect(['controller' => 'Users', 'action' => 'login']);
            }
        }
    
    }
 

UsersTable

 <?php

class UsersTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');
    }

    /**
     * Default validation rules.
     *
     * @param CakeValidationValidator $validator Validator instance.
     * @return CakeValidationValidator
     */
    public function validationDefault(Validator $validator): Validator
    {
        return $validator
            ->notEmpty('username', 'A username is required')
            ->email('username')
            ->notEmpty('password', 'A password is required')
            ->notEmpty('role', 'A role is required')
            ->add('role', 'inList', [
                'rule' => ['inList', ['admin', 'author']],
                'message' => 'Please enter a valid role'
            ]);
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param CakeORMRulesChecker $rules The rules object to be modified.
     * @return CakeORMRulesChecker
     */
    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['username']), ['errorField' => 'username']);

        return $rules;
    }
}
 

Пользователи

 class User extends Entity
{
    // Make all fields mass assignable for now.
    protected $_accessible = ['*' => true];

    // ...

    protected function _setPassword($password)
    {
        if (strlen($password) > 0) {
            return (new DefaultPasswordHasher)->hash($password);
        }
    }
    /**
     * Fields that are excluded from JSON versions of the entity.
     *
     * @var array
     */
    protected $_hidden = [
        'password',
    ];
}
 

Комментарии:

1. Посмотрите в журналах, в приложении config установите debug в true и отправьте журналы ошибок на ваш вопрос.

2. Вы имеете в виду салины в boostrap CLI?

3. Нет, вам нужно посмотреть app/logs/error.log

4. я отредактировал свой пост с помощью stacktrace в error.log.

Ответ №1:

Очевидно, вы неправильно или каким-либо образом внедрили промежуточное программное обеспечение аутентификации.

Вот полные инструкции о том, как это сделать:

https://book.cakephp.org/authentication/2/en/index.html