Cakephp 3.7, промежуточное ПО, аутентификация и маршрутизация - PullRequest
0 голосов
/ 23 мая 2019

Я использую Cakephp 3.7 и промежуточное ПО для аутентификации.

Мое приложение размещено локально на http://192.168.33.10/scoring.

Я использую следующий метод промежуточного программного обеспечения в моем 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;


use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
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\Routing\Router;
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.
*/
class Application extends BaseApplication implements 
AuthenticationServiceProviderInterface
{
/**
 * {@inheritDoc}
 */
public function bootstrap()
{

    $this->addPlugin('CakeDC/Enum');

    $this->addPlugin('Muffin/Trash');

    $this->addPlugin('AuditStash');

    // Call parent to load bootstrap from files.
    parent::bootstrap();

    // include required plugins
    $this->addPlugin('Authentication');

    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);
    }
}

/**
 * Returns a service provider instance.
 *
 * @param \Psr\Http\Message\ServerRequestInterface $request Request
 * @param \Psr\Http\Message\ResponseInterface $response Response
 * @return \Authentication\AuthenticationServiceInterface
 */
public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
{
    $service = new AuthenticationService();

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

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

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

    return $service;
}

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

    // Add the authentication middleware
    $authentication = new AuthenticationMiddleware($this, [
        'unauthenticatedRedirect' => Router::url(['controller' => 'Users', 'action' => 'login']),
    ]);

    $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 to the middleware queue
        ->add($authentication);

    return $middlewareQueue;
}

}

У меня есть следующее в config / rout.php:

<?php
    /**
     * Routes configuration
     *
     * In this

 file, you set up routes to your controllers and their actions.
 * Routes are very important mechanism that allows you to freely connect
 * different URLs to chosen controllers and their actions (functions).
 *
 * 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
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

/**
 * The default class to use for all routes
 *
 * The following route classes are supplied with CakePHP and are appropriate
 * to set as the default:
 *
 * - Route
 * - InflectedRoute
 * - DashedRoute
 *
 * If no call is made to `Router::defaultRouteClass()`, the class used is
 * `Route` (`Cake\Routing\Route\Route`)
 *
 * Note that `Route` does not do any inflections on URLs which will result in
 * inconsistently cased URLs when used with `:plugin`, `:controller` and
 * `:action` markers.
 *
 * Cache: Routes are cached to improve performance, check the RoutingMiddleware
 * constructor in your `src/Application.php` file to change this behavior.
 *
 */
Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    // Register scoped middleware for in scopes.
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    /**
     * Apply a middleware to the current route scope.
     * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
     */
    $routes->applyMiddleware('csrf');

    /**
     * Here, we are connecting '/' (base path) to a controller called 'Pages',
     * its action called 'display', and we pass a param to select the view file
     * to use (in this case, src/Template/Pages/home.ctp)...
     */
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    //connect login route
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);

    //connect logout route
    $routes->connect('/logout', ['controller' => 'Users', 'action' => 'logout']);

    /**
     * ...and connect the rest of 'Pages' controller's URLs.
     */
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    /**
     * Connect catchall routes for all controllers.
     *
     * Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for
     *
     * ```
     * $routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']);
     * $routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']);
     * ```
     *
     * Any route class can be used with this method, such as:
     * - DashedRoute
     * - InflectedRoute
     * - Route
     * - Or your own route class
     *
     * You can remove these routes once you've connected the
     * routes you want in your application.
     */
    $routes->fallbacks(DashedRoute::class);
});

/**
 * If you need a different set of middleware or none at all,
 * open new scope and define routes there.
 *
 * ```
 * Router::scope('/api', function (RouteBuilder $routes) {
 *     // No $routes->applyMiddleware() here.
 *     // Connect API actions here.
 * });
 * ```
 */

Router::prefix('admin', function ($routes) {
    // All routes here will be prefixed with `/admin`
    // And have the prefix => admin route element added.

    $routes->fallbacks(DashedRoute::class);


});

У меня проблема в том, что перенаправление идет на http://192.168.33.10/login, а не на http://192.168.33.10/scoring/login.

При устранении неполадок в моей проблеме я обнаружил, что метод Router :: url вернет / login, если он будет запущен в Application.php, но вернет / scoring / login, если он будет запущен из AppController.php.

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

Может кто-нибудь помочь определить мою ошибку?

...