CakePHP 3.7 CakePHP / плагин аутентификации.Ошибка «Требуется аутентификация для продолжения» - PullRequest
0 голосов
/ 28 июня 2019

Я следую указаниям в кулинарной книге https://book.cakephp.org/authentication/1.1/en/index.html. Однако мой код продолжает выдавать ошибки введите описание изображения здесь

Это мой Application.php

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link      https://cakephp.org CakePHP(tm) Project
 * @since     3.3.0
 * @license   https://opensource.org/licenses/mit-license.php MIT License
 */
namespace App;

/**
 * AUTHENTICATION SETTINGS
 */
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;

/**
 * AUTHENTICATION SETTINGS
 */
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\Http\Middleware\CsrfProtectionMiddleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;





/**
 * Application setup class.
 *
 * This defines the bootstrapping logic and middleware layers you
 * want to use in your application.
 */
//OLD -- class Application extends BaseApplication

class Application extends BaseApplication
implements AuthenticationServiceProviderInterface
{
    /**
     * {@inheritDoc}
     */

     public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
     {
         $service = new AuthenticationService();

         $fields = [
             'username' => 'email',
             'password' => 'password'
         ];

         // Load identifiers
         $service->loadIdentifier('Authentication.Password', compact('fields'));

         // Load the authenticators, you want session first
         $service->loadAuthenticator('Authentication.Session');
         $service->loadAuthenticator('Authentication.Form', [
             'fields' => $fields,
             'loginUrl' => '/users/login'
         ]);

         return $service;
     }

    public function bootstrap()
    {

        parent::bootstrap();
        $this->addPlugin('DebugKit');
        $this->addPlugin('Authentication');

        // Call parent to load bootstrap from files.
        //-- Authentication plugin added change the Auth function


        if (PHP_SAPI === 'cli') {
            try {
                $this->addPlugin('Bake');
            } catch (MissingPluginException $e) {
                // Do not halt if the plugin is missing
            }

            $this->addPlugin('Migrations');
        }

        /*
         * 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\Plugin::class);
        }
    }

    /**
     * Setup the middleware queue your application will use.
     *
     * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
     * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
     */
    public function middleware($middlewareQueue)
    {
        $middlewareQueue
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(new ErrorHandlerMiddleware(null, Configure::read('Error')))

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(new AssetMiddleware([
                'cacheTime' => Configure::read('Asset.cacheTime')
            ]))

            // Add routing middleware.
            // Routes collection cache enabled by default, to disable route caching
            // pass null as cacheConfig, example: `new RoutingMiddleware($this)`
            // you might want to disable this cache in case your routing is extremely simple
            ->add(new RoutingMiddleware($this, '_cake_routes_'));


         // Add the authentication middleware
         $authentication = new AuthenticationMiddleware($this,[
           'unauthorizedRedirect' => '/',
           'queryParam' => null,
         ]);


         // Add the middleware to the middleware queue
         $middlewareQueue->add($authentication);

        return $middlewareQueue;
    }
}

Внутри моего app / Application.php у меня есть вызов Аутентификация Плагин внутри Функция начальной загрузки примерно так

    public function bootstrap()
    {

        parent::bootstrap();
        $this->addPlugin('DebugKit');
        $this->addPlugin('Authentication');

и внутри моего AppController.php Я настроил это так


/** INITIALIZE  **/
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        /**
        *$this->loadComponent('Flash');
        *
         * load authenticator
         * [$this->loadComponent description]
         * @var [type]
         *
         */
         $this->loadComponent('Authentication.Authentication', [
             'logoutRedirect' => false // Default is false
         ]);


/** INITIALIZE  **/

}

и мой UsersController.php тот, который обрабатывает запрос, поступающий с https: localhost / users / login

    public function login()
     {

       //$this->render(false);



      $this->viewBuilder()->layout('Common/login');
    $session = $this->request->session();

      /*
      **AUTHENTICATION
       */
       $result = $this->Authentication->getResult();
      debug($result);

          // regardless of POST or GET, redirect if user is logged in
          if ($result->isValid()) {
              $user = $request->getAttribute('identity');

              // Persist the user into configured authenticators.
              $this->Authentication->setIdentity($user);
              $session->write('user_data',$user);

              $redirect = $this->request->getQuery('redirect', ['controller' => 'Users', 'action' => 'display', 'index']);
              return $this->redirect($redirect);
          }

          // display error if user submitted and authentication failed
          if ($this->request->is(['post']) && !$result->isValid()) {
              $this->Flash->error('Invalid username or password');
          }
       /*
       **AUTHENTICATION
        */

    }

Я занимаюсь этим часами, мне нужна помощь, ребята :).

1 Ответ

0 голосов
/ 05 июля 2019

Вы должны определить разрешающее действие для неавторизованных действий в beforeFilter, например:

$this->Authentication->allowUnauthenticated(['login']);

...