Событие ответа API zf2, перехваченное bjyauthorize

Привет, может ли кто-нибудь помочь мне предотвратить bjyauthorize, чтобы поймать мою ошибку события API?

bjyauthorize перенаправляет незарегистрированного пользователя на форму входа, добавленную в конфигурацию. Но поскольку мой API разрешен для всех ролей, даже для гостя, я просто хочу, чтобы он возвращал сообщение об ошибке Json, перехваченное ApiProblemListener

ApplicationRest\Module.php

class Module implements
    ConfigProviderInterface, 
    AutoloaderProviderInterface
{

    public function onBootstrap(MvcEvent $e)
    {
        $app = $e->getApplication();
        $sm = $app->getServiceManager();
        $events = $app->getEventManager();

        $listener = $sm->get('ApplicationRest\ApiAuthenticationListener');
        $events->getSharedManager()->attach('ApplicationRest\Controller', 'dispatch', $listener, 500);

        $events->attach('render', array($this, 'onRender'), 100);
        $events->attach($sm->get('ApplicationRest\ApiProblemListener'));
    }

    /**
     * Listener for the render event
     * Attaches a rendering/response strategy to the View.
     *
     * @param  \Zend\Mvc\MvcEvent $e
     */
    public function onRender($e)
    {
        $result = $e->getResult();
        if (!$result instanceof RestfulJsonModel) {
            return;
        }
        //var_dump(123);exit();


        $app = $e->getTarget();
        $services = $app->getServiceManager();
        $view = $services->get('View');
        $restfulJsonStrategy = $services->get('ApplicationRest\RestfulJsonStrategy');
        $events = $view->getEventManager();

        // register at high priority, to "beat" normal json strategy registered
        // via view manager
        $events->attach($restfulJsonStrategy, 500);
    }
}

У меня много модулей, и я действительно думаю перенести свой apiModule «ApplicationRest» в другой проект, но на самом деле не хочу обновлять модель и сервис каждый раз, когда я делаю некоторые обновления в основном проекте.

Любые предложения приветствуются! Спасибо за ваше время!

EDIT: предоставлен дополнительный класс HeaderAuthentication.

class HeaderAuthentication implements AdapterInterface
{

    const AUTHORIZATION_HEADER = 'Authorization';
    const CRYPTO = 'sha256';

    protected $request;
    protected $repository;

    public function __construct(RequestInterface $request, UserRepository $repository)
    {
        $this->request = $request;
        $this->repository = $repository;
    }

    /**
     * Authorization: Key={key} Timestamp={timestamp} Signature={signature}
     * @return Result
     */
    public function authenticate()
    {
        $request = $this->getRequest();
        if (!$request instanceof Request) {
            return;
        }
        $headers = $request->getHeaders();

        // Check Authorization header presence
        if (!$headers->has(static::AUTHORIZATION_HEADER)) {
            return new Result(Result::FAILURE, null, array(
                'Authorization header missing'
            ));
        }

        $authorization = $headers->get(static::AUTHORIZATION_HEADER)->getFieldValue();

        // Validate public key
        $publicKey = $this->extractPublicKey($authorization);
        $user = $this->getUserRepository()
                     ->findOneByApiSecret($publicKey);

        if (null === $user) {
            $code = Result::FAILURE_IDENTITY_NOT_FOUND;
            return new Result($code, null, array(
                'User not found based on public key'
            ));
        }

        // Validate signature
        $signature = $this->extractSignature($authorization);
        /*$hmac = $this->getHmac($request, $user);
        if ($signature !== $hmac) {
            $code = Result::FAILURE_CREDENTIAL_INVALID;
            return new Result($code, null, array(
                'Signature does not match'
            ));
        }*/

        return new Result(Result::SUCCESS, $user);
    }
}

ApiAuthenticationListener

class ApiAuthenticationListener
{

    protected $adapter;

    public function __construct(HeaderAuthentication $adapter)
    {
        $this->adapter = $adapter;
    }

    public function __invoke(MvcEvent $event)
    {
        $result = $this->adapter->authenticate();

        if (!$result->isValid()) {
            $response = $event->getResponse();

            // Set some response content
            $response->setStatusCode(401);
            return $response;
        }

        // All is OK
        $event->setParam('user', $result->getIdentity());
    }

}

person Marcel Djaman    schedule 10.06.2015    source источник
comment
Я не уверен, что вы спрашиваете. Не могли бы вы немного подробнее рассказать о проблеме?   -  person Ankh    schedule 10.06.2015
comment
Предотвращает ли bjy ЛЮБОЙ запрос к API?   -  person Valentin Rusk    schedule 10.06.2015
comment
@ValentinRusk нет, так как я разрешил все API-контроллеры с помощью bjyauthorize   -  person Marcel Djaman    schedule 10.06.2015
comment
Проблема @Svengali возникла, когда возникла ошибка при проверке авторизации API.   -  person Marcel Djaman    schedule 10.06.2015
comment
@Svengali, возможно, добавить маршрут ошибки, чтобы разрешить гостевой доступ?   -  person Valentin Rusk    schedule 10.06.2015
comment
добавлены некоторые правки в вопрос с большим количеством классов   -  person Marcel Djaman    schedule 10.06.2015


Ответы (1)


Я предполагаю, что вы установили охрану на своем маршруте. Вам нужно сообщить BJYAuthorize через конфигурацию вашего модуля, что этот контроллер или маршрут не должны быть защищены.

'bjyauthorize' => [

    'default_role'          => 'guest',

    ...     

    'guards' => [
        'BjyAuthorize\Guard\Controller' => [

            // system tools
            ['controller' => 'Application\Controller\Api', 'roles' => [] ],

            ['controller' => 'error', 'roles' => []],

        ],
    ],
],

Я вырезал мелкие детали, относящиеся к конкретному приложению, но такие проблемы быстро решаются. У меня была аналогичная потребность в том, чтобы маршруты CLI не были защищены тем, что в противном случае является http auth.

person Saeven    schedule 10.06.2015