使用Symfony2的AccessDeniedHandlerInterface

Pat*_*gle 15 security authentication symfony

我试图获得Symfony2的我的安全的东西设置,我有它到目前为止的工作,但现在我需要做一些更花哨的东西.我目前正在使用处理PreAuthentication的所有内容(我使用第三方组件进行登录和会话管理).该部分与JMS安全捆绑包一起工作得很好.

现在我想要抓住投掷403s的用户,以便我可以将它们转发到我正在使用的第三方组件的登录页面.我认为我最好的办法是在异常监听器中添加一个异常处理程序.我正在查看AccessDeniedHandlerInterface.

  1. 这是我走向正确的方向吗?
  2. 如何将此处理程序添加到异常侦听器?

编辑:我最后做了类似的事情.我创建了一个在kernel.exception事件上提示的服务.services.yml看起来像这样:

services:
   kernel.listener.accessDenied:
    class: Fully\Qualified\Namespace\Path\To\Class
    tags:
      - { name: kernel.event_listener, event: kernel.exception, method: onAccessDeniedException }
Run Code Online (Sandbox Code Playgroud)

和它自己的课程:

<?php

namespace Fully\Qualified\Namespace\Path\To;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent,
Symfony\Component\HttpFoundation\Response,
Symfony\Component\Security\Core\Exception\AccessDeniedException;

class Class
{
  public function onAccessDeniedException(GetResponseForExceptionEvent $event)
  {
    $exception = $event->getException();
    //Get the root cause of the exception.
    while (null !== $exception->getPrevious()) {
      $exception = $exception->getPrevious();
    }
    if ($exception instanceof AccessDeniedException) {
      //Forward to third-party.
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Jov*_*vic 21

这听起来很对.

或者,如果您对AccessDeniedException特别感兴趣,您还可以access_denied_handler在防火墙内定义security.yml:

security:
    firewalls:
        my_firewall:
            # ...
            access_denied_handler: kernel.listener.access_denied.handler
            # ...
Run Code Online (Sandbox Code Playgroud)

然后在您services.xml或同等中定义您的服务:

<parameters>
    <parameter key="kernel.listener.security.class">Path\To\Your\Class</parameter>
</parameters>

<service id="kernel.listener.access_denied.handler" class="%kernel.listener.security.class%">
    <tag name="kernel.event_listener" event="security.kernel_response" method="handle" />
</service>
Run Code Online (Sandbox Code Playgroud)

处理程序类:

use \Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;

class MyAccessDeniedHandler implements AccessDeniedHandlerInterface
{
    public function handle(Request $request, AccessDeniedException $accessDeniedException)
    {
        // do something with your exception and return Response object (plain message of rendered template)
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到Symfony2的完整安全性参考:http://symfony.com/doc/2.8/reference/configuration/security.html