FOSRestBundle没有捕获异常

时间:2013-07-04 14:33:14

标签: symfony fosrestbundle

我正在尝试设置FOSRestBundle来捕获身份验证异常。我的配置:

fos_rest:
  param_fetcher_listener: true
  body_listener: true
  format_listener: true
  view:
    default_engine: php
  format_listener:
    default_priorities: ['json']
    fallback_format: json
    prefer_extension: false
  access_denied_listener:
    json: true
  exception:
    codes:
      Symfony\Component\Security\Core\Exception\AccessDeniedException: 403

twig:
  exception_controller: FOS\RestBundle\Controller\ExceptionController::showAction

此配置将在控制器中抛出异常时捕获异常,但在安全组件中抛出异常时(即,如果用户身份验证失败)则不会捕获异常。我的配置有问题,或者FOSRestBundle是不是设计用于拦截堆栈中该点的异常?

值得一提的是,我在这里使用基于WSSE教程的自定义身份验证提供程序:

http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html

2 个答案:

答案 0 :(得分:0)

身份验证异常通常应由身份验证失败处理程序服务处理。

可以在security.yml中找到身份验证处理程序:

security:
    firewalls:
       firewall_name:
           form_login:
               # ...
               failure_path:    /foo
               failure_forward: false
               failure_path_parameter: _failure_path
               failure_handler: some.service.id
               success_handler: some.service.id

请参阅configuration reference

有关如何实施自己的失败处理程序的信息,请参阅this question

答案 1 :(得分:0)

我遇到了同样的问题。我的问题是WsseListener实际上没有抛出异常。他们的教程有以下代码:

try {
            $authToken = $this->authenticationManager->authenticate($token);
            $this->securityContext->setToken($authToken);

        return;
    } catch (AuthenticationException $failed) {
        // ... you might log something here

        // To deny the authentication clear the token. This will redirect to the login page.
        // Make sure to only clear your token, not those of other authentication listeners.
        // $token = $this->securityContext->getToken();
        // if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
        //     $this->securityContext->setToken(null);
        // }
        // return;

        // Deny authentication with a '403 Forbidden' HTTP response
        $response = new Response();
        $response->setStatusCode(403);
        $event->setResponse($response);

    }

    // By default deny authorization
    $response = new Response();
    $response->setStatusCode(403);
    $event->setResponse($response);
}

请注意如何捕获AuthenticationException,然后返回HTTP响应。

我通过抛出$ failed来修复我的错误:

catch (AuthenticationException $failed) {
     throw $failed
}