如何从CakePHP AuthComponent返回自定义错误?

问题描述 投票:0回答:1

我正在根据此处列出的文档向当前的CakePHP应用程序中添加一个CakePHP 3身份验证组件:

https://book.cakephp.org/3/en/controllers/components/authentication.html

我正在按照此示例处理错误消息的显示:

https://book.cakephp.org/3/en/controllers/components/authentication.html#identifying-users-and-logging-them-in

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Flash->error(__('Username or password is incorrect'));
        }
    }
}

我将在此处的文档中集成auth组件,如果可以对用户进行身份验证,则将返回用户数据数组;如果未对用户数据进行身份验证,则将返回false(按照文档中的指定:]

https://book.cakephp.org/3/en/controllers/components/authentication.html#creating-custom-authentication-objects

namespace App\Auth;

use Cake\Auth\BaseAuthenticate;
use Cake\Http\ServerRequest;
use Cake\Http\Response;

class OpenidAuthenticate extends BaseAuthenticate
{
    public function authenticate(ServerRequest $request, Response $response)
    {
        // Do things for OpenID here.
        // Return an array of user if they could authenticate the user,
        // return false if not.

        if($failureCondition) {
            return false;
        }

        return $user;
    }
}

但是我想动态确定auth组件中的错误:

namespace App\Auth;

use Cake\Auth\BaseAuthenticate;
use Cake\Http\ServerRequest;
use Cake\Http\Response;

class OpenidAuthenticate extends BaseAuthenticate
{
    public function authenticate(ServerRequest $request, Response $response)
    {
        if($failureConditionA) {
            $this->error = 'Error A'; 
            return false;
        }

        if($failureConditionB) {
            $this->error = 'Error B'; 
            return false;
        }

        return $user;
    }
}

并像这样在Flash消息中打印动态产生的错误:

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            // 'Error A' or 'Error B' displayed on failure
            $this->Flash->error($this->Auth->error());
        }
    }
}

用于执行此操作的正确代码是什么?

如果这违反了AuthComponent应该如何工作的意图,我很想对此进行解释和/或知道执行此操作的任何其他正确方法?

提前感谢!

php authentication cakephp cakephp-3.x
1个回答
1
投票
有很多方法可以解决此问题,最简单的方法可能是获取特定的身份验证对象,并通过需要实现的公共API访问对象存储的错误,例如,您的身份验证者可以公开一个getError()方法,那么您可以在控制器中执行以下操作:

$openIdAuth = $this->Auth->getAuthenticate('Openid'); $error = $openIdAuth->getError();

对于更复杂的东西,您可以实现一个自定义/扩展的身份验证组件,您可以在其中访问身份验证对象的完整列表,并且可以轻松地访问链中的最后一个对象并返回它所保存的可能的错误信息。

如果您要在尚未使用任何身份验证的应用程序中实现身份验证,那么我非常非常强烈建议您放弃已弃用的身份验证组件,而改用新的authentication plugin!它更清洁,用途更广泛,并且returning error details可以立即使用。
© www.soinside.com 2019 - 2024. All rights reserved.