【问题标题】:CakePHP 3.7 cakephp/authentication plugin. Error "Authentication is required to continue "CakePHP 3.7 cakephp/认证插件。错误“需要身份验证才能继续”
【发布时间】:2019-06-28 07:48:01
【问题描述】:

我正在遵循烹饪书 https://book.cakephp.org/authentication/1.1/en/index.html 中的指南。但是我的代码不断抛出错误enter image description here

这是我的 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 中,我已经在 function bootstrap 中调用了 Authentication 插件,就像这样

    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
        */

    }

我已经做了好几个小时了,在这方面需要帮助:)。

【问题讨论】:

  • 显然您没有通过身份验证,即身份验证失败或未执行。您没有表明您正在从需要身份验证的操作中排除 login 操作!?还有来自您的引导程序(可能还有您的登录操作)的输出,这将导致会话 cookie 标头不被发送。此外,不需要手动保存身份,身份验证服务会自动完成。
  • 我是否需要创建一个控制器来显示将数据发送到 /users/login 的登录表单?
  • 如果您想使用表单,当然,您需要一个显示表单的控制器。通常,您已经拥有的控制器会在登录操作中呈现表单。但同样,您似乎并没有从需要身份验证的操作中排除 login 操作(或者您可能只是没有显示所有代码)。
  • 您使用的是 3.x 版本还是 1.x?看来您问的是 3.x 问题,但使用的是 1.x 代码文档。对于 3.x:book.cakephp.org/3.0/en/controllers/components/…
  • @JulyanoFelipe 文档与官方认证插件有关,这是认证 CakePHP 应用程序的新方法。当前版本是 1.1,至少需要 CakePHP 3.7。您链接到的文档已被弃用。

标签: php cakephp cakephp-3.0


【解决方案1】:

您应该在 beforeFilter 中为非授权操作定义允许操作,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2023-03-08
    • 2014-05-11
    • 2013-11-10
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多