doushouj966020 2019-06-28 07:48
浏览 159

CakePHP 3.7 cakephp / authentication插件。 错误“需要验证才能继续”

I am following the guideline inside the cook book https://book.cakephp.org/authentication/1.1/en/index.html. However my code keeps throwing errors enter image description here

This is my 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;
    }
}

Inside my app/Application.php i have call the Authentication plugin inside function bootstrap like so

    public function bootstrap()
    {

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

and inside my AppController.php i have set it up like this


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

}

and my UsersController.php the one that handles the request coming from 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
        */

    }

I have been at it for hours, need help on this one guys :) .

  • 写回答

1条回答 默认 最新

  • doukan5332 2019-07-05 10:56
    关注

    You should define allow action for non authorized actions in beforeFilter, for example:

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

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题