0

我已经定义了我的控制器,但我想保护所有这些控制器,如下所示:

// In my Controller Class 
public function chooseDateAction()
{
    if($this->get('MY.roles_features')
            ->isGranted($this->container->get('request')->get('_route')))
    {
         // Do something 

    }
    else
    {
        throw new AccessDeniedException();
    }


    return array( );
}

我必须设计自己的“isGranted”功能,因为roles它是动态的。顺便说一句,该功能工作正常!

所以我的问题是我是否必须isGranted在我的所有功能中重复该功能,Controllers或者我可以将它放在某个地方以减少代码冗余。

我知道我必须放置isGranted在我的安全的一些顶层,但问题是如何以及在哪里?

4

1 回答 1

5

尝试编写一个基本控制器,它将检查构造,如果isGranted方法通过,否则抛出异常。例如:

<?php

namespace Acme\DolanBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class BaseController extends Controller
{

    public function __construct()
    {
         if(!$this->get('MY.roles_features')
                  ->isGranted($this->container->get('request')->get('_route')))
        {
         throw new AccessDeniedException('Gooby pls');
        }
    }
}

然后只需在其他控制器中扩展 BaseController 即可。

于 2012-06-16T10:21:20.933 回答