You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CakePHP4+PHPUnit登录测试报FAILURE_CREDENTIALS_MISSING错误求助

问题:CakePHP4+PHPUnit登录测试返回FAILURE_CREDENTIALS_MISSING错误

使用CakePHP4结合PHPUnit对UserController做登录测试时,提交参数后一直返回FAILURE_CREDENTIALS_MISSING错误,尝试过多种参数组合(比如用username键、明文密码等)都没解决。


测试代码

public function testLogin(): void
{
    $this->enableSecurityToken();
    $this->enableCsrfToken();
    $this->get('/user/login');
    $this->assertResponseOk();

    $this->post('/user/login', [
        'DNI_CIF' => '22175395Z',
        'password' => '$2y$10$ND67aMGqm.qK86MW1wuW9OQLC9vyJQGUn2HnLuSInwrFbXQKBT.V.'
    ]);

    $this->assertResponseCode(302); //Si correcto redirige
//    $this->assertSession(1, 'Auth.User.id');
}

UserController代码

public function login()
{
    $this->request->allowMethod(['get', 'post']);
    $result = $this->Authentication->getResult();
    // regardless of POST or GET, redirect if user is logged in
    if ($result && $result->isValid()) {
     return $this->redirect('/');
    }
    // display error if user submitted and authentication failed
    if ($this->request->is('post') && !$result->isValid()) {
        $this->Flash->error(__('Alias de usuario o contraseña incorrecta.'));
    }
}

Application身份验证配置

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    $authenticationService = new AuthenticationService([
        'unauthenticatedRedirect' => Router::url('/user/login'),
        'queryParam' => 'redirect',
    ]);

    // Load identifiers, ensure we check email and password fields
    $authenticationService->loadIdentifier('Authentication.Password', [
        'resolver' => [
            'className' => 'Authentication.Orm',
            'userModel' => 'User',
            ],
        'fields' => [
            'username' => 'DNI_CIF',
            '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' => 'DNI_CIF',
            'password' => 'password',
        ],
        'loginUrl' => Router::url('/user/login'),
    ]);

    return $authenticationService;
}

错误信息

.......object(Authentication\Authenticator\Result)#826 (3) {
  ["_status":protected]=>
  string(27) "FAILURE_CREDENTIALS_MISSING"
  ["_data":protected]=>
  NULL
  ["_errors":protected]=>
  array(1) {
    [0]=>
    string(27) "Login credentials not found"
  }
}

排查与解决方法

  1. 调整POST参数结构
    CakePHP的Form认证器默认会读取模型嵌套的参数(和前端表单提交格式一致),把测试中的POST数据改成模型数组结构,同时注意使用明文密码(认证器会自动与数据库哈希值比对,直接传哈希值会验证失败):
$this->post('/user/login', [
    'User' => [
        'DNI_CIF' => '22175395Z',
        'password' => '你的明文密码'
    ]
]);
  1. 确认请求参数是否被正确接收
    在测试中临时打印请求数据,排查参数是否被过滤或结构错误:
$this->post('/user/login', [...]);
debug($this->getRequest()->getData()); // 查看提交的参数内容
  1. 临时禁用Security组件验证
    Security组件可能因Token不匹配拦截请求,测试环境可临时关闭验证:
$this->disableSecurityToken();
$this->disableCsrfToken();
// 或直接移除Security组件监听
$this->getEventManager()->off($this->Security);
  1. 验证路由与登录URL一致性
    确认Router::url('/user/login')生成的URL和测试中使用的/user/login完全一致,避免路由前缀、子目录等导致认证器无法识别登录请求。

  2. 检查数据库用户数据
    确保数据库中存在DNI_CIF为22175395Z的用户,且密码哈希值正确。可在认证配置中临时添加调试代码,确认Resolver能找到用户:

// 在getAuthenticationService方法中添加
$resolver = $authenticationService->getIdentifier('Authentication.Password')->getResolver();
$user = $resolver->find(['DNI_CIF' => '22175395Z']);
debug($user);

内容的提问来源于stack exchange,提问作者Iria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:10:43