В настоящее время я реализую функцию входа в систему в CakePHP4. Поэтому я хотел разделить его на модель обычного пользователя и модель административного пользователя.
Я вообще не знал, как это сделать, и потратил весь день на поиск способов реализовать это, но не мог 'Не делайте этого.
Я хочу настроить аутентификацию в «routes. php», но у меня проблемы с «реализацией AuthenticationServiceProviderInterface» в «Application. php». Что мне делать?
// routes.php
$routes->scope('/', function (RouteBuilder $builder) {
/......./
// ログイン
//$builder->connect('mgt-account/*', ['controller' => 'MgtAccount', 'action' => 'login', 'prefix' => 'Admin']);
$builder->connect('users/*', ['controller' => 'Users', 'action' => 'login', 'prefix' => 'Normal']);
/......./
});
$routes->prefix('Normal', function (RouteBuilder $routes) {
$loginUrl = Router::url('/normal/users/login');
$fields = [
'username' => 'mail',
'password' => 'password',
];
$service = new AuthenticationService([
'unauthenticatedRedirect' => $loginUrl,
'queryParam' => 'redirect',
]);
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => $loginUrl,
]);
$service->loadIdentifier('Authentication.Password', compact('fields'));
$routes->registerMiddleware(
'auth',
new \Authentication\Middleware\AuthenticationMiddleware($service)
);
$routes->applyMiddleware('auth');
//$routes->connect('/:controller');
$routes->fallbacks(DashedRoute::class);
});
$routes->prefix('Admin', function (RouteBuilder $routes) {
$loginUrl = Router::url('/admin/mgt-account/login');
$fields = [
'username' => 'mail',
'password' => 'password',
];
$service = new AuthenticationService([
'unauthenticatedRedirect' => $loginUrl,
'queryParam' => 'redirect',
]);
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => $loginUrl,
]);
$service->loadIdentifier('Authentication.Password', compact('fields'));
$routes->registerMiddleware(
'auth',
new \Authentication\Middleware\AuthenticationMiddleware($service)
);
$routes->applyMiddleware('auth');
//$routes->connect('/:controller');
$routes->fallbacks(DashedRoute::class);
});
<?php
// src/Application.php
declare(strict_types=1);
namespace App;
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
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
// I really want to comment out and delete this bottom.
implements AuthenticationServiceProviderInterface
{
/**
* Load all the application configuration and bootstrap logic.
*
* @return void
*/
public function bootstrap(): void
{
// Call parent to load bootstrap from files.
parent::bootstrap();
if (PHP_SAPI === 'cli') {
$this->bootstrapCli();
}
/*
* 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');
}
// Load more plugins here
}
/**
* 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): MiddlewareQueue
{
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(Configure::read('Error')))
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime'),
]))
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance. For that when
// creating the middleware instance specify the cache config name by
// using it's second constructor argument:
// `new RoutingMiddleware($this, '_cake_routes_')`
->add(new RoutingMiddleware($this))
// I really want to comment out and delete this bottom.
->add(new AuthenticationMiddleware($this));
return $middlewareQueue;
}
/**
* Bootrapping for CLI application.
*
* That is when running commands.
*
* @return void
*/
protected function bootstrapCli(): void
{
try {
$this->addPlugin('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
$this->addPlugin('Migrations');
// Load more plugins here
}
// I really want to comment out and delete this bottom.
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => '/normal/users/login',
'queryParam' => 'redirect',
]);
$authenticationService->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'mail',
'password' => 'password',
]
]);
$authenticationService->loadAuthenticator('Authentication.Session');
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'mail',
'password' => 'password',
],
'loginUrl' => '/normal/users/login',
]);
return $authenticationService;
}
}
Поскольку я впервые использую «stackoverflow», я не уверен, как задать хороший вопрос. Я был бы признателен, если бы вы могли мне помочь.
Я был бы признателен, если бы вы могли указать мне на это.
спасибо.