使用Annotation保护Symfony2 Controller的操作免受未经授权的请求

dan*_*rvt 0 php python annotations decorator symfony

Controller's Action当用户未使用自定义注释登录时,我似乎无法确定是否可以保护.

这就是我想要实现的目标:

...
class FooController extends Controller
{
    ...

    /*
    * The code bellow should only be executed if the user 
    * is authorized, otherwise should throw an exception 
    * or something.
    *
    * @Authorized
    */
    public function barAction($cid) {
        // do stuff only if user is authorized
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用某种" 装饰器设计模式 " 来做到这一点,但我真正想要的是更像Python的使用PHP 注释装饰器

这是真的吗?我该怎么办?

A L*_*Lee 5

如果您正在使用SensioFrameworkExtraBundle,则可以注释控制器类.从他们的例子来看

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class PostController extends Controller
{
    /**
     * @Security("has_role('ROLE_ADMIN')")
     */
    public function indexAction()
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是JMSSecurityExtraBundle保护您的服务层,例如,

namespace Acme\HelloBundle\Newsletter;

use JMS\SecurityExtraBundle\Annotation\Secure;
// ...

class NewsletterManager
{

    /**
     * @Secure(roles="ROLE_NEWSLETTER_ADMIN")
     */
    public function sendNewsletter()
    {
        // ...
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)