首页 > 解决方案 > cakephp4身份验证登录不起作用

问题描述

我正在测试 cakephp 4 登录身份验证。我从 cakephp4 教程身份验证中复制了所有代码(链接见下文),并根据需要将所有代码复制到我的项目中,没有发现错误。

我可以创建新的登录名,但实际上我仍然无法登录。我的 cakephp4 项目如下(它只是一个使用测试数据的测试项目,目的是试图让登录工作)

https://southernservices.com.au/crm4/users/login

This is the code where things get stuck

public function login()
{
    $this->request->allowMethod(['get', 'post']);
   $result = $this->Authentication->getResult();
    
 
    // regardless of POST or GET, redirect if user is logged in
    debug($result); //debug of output
    if ($result->isValid()) {
        // redirect to /articles after login success
        $redirect = $this->request->getQuery('redirect', [
            'controller' => 'Articles',
            'action' => 'index',
        ]);
        $this->Flash->success(__('Logged In!'));
        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'));
    }
   
}

in application.php here is the main function for authentication
  public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    $authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => '/users/login',
        'queryParam' => 'redirect',
    ]);

    // Load identifiers, ensure we check email and password fields
    $authenticationService->loadIdentifier('Authentication.Password', [
        'fields' => [
            'username' => 'email',
            'password' => 'password',
        ]
    ]);

    // Load the authenticators, you want session first
    $authenticationService->loadAuthenticator('Authentication.Session');
    // Configure form data check to pick email and password
    $authenticationService->loadAuthenticator('Authentication.Form', [
        'fields' => [
            'username' => 'email',
            'password' => 'password',
        ],
        'loginUrl' => '/users/login',
    ]);

    return $authenticationService;
}

https://book.cakephp.org/4/en/tutorials-and-examples/cms/authentication.html

标签: cakephpcakephp-3.0cakephp-4.x

解决方案


调试输出:

登录 URLhttps://southernservices.com.au/crm4/users/login不匹配/users/login。'

改变:

'/users/login',

至:

'/crm4/users/login'

或者

Router::url(['controller' => 'Users', 'action' => 'login']);

不要忘记:

use Cake\Routing\Router;

推荐阅读