【问题标题】:Protect a Symfony2 Controller's action from unauthorized requests with an Annotation使用注释保护 Symfony2 控制器的操作免受未经授权的请求
【发布时间】:2014-07-03 05:16:54
【问题描述】:

当用户未使用自定义注释登录时,我似乎无法确定是否可以保护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
    }

    ...
}

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

这可能吗?我该怎么做?

【问题讨论】:

    标签: php python symfony annotations decorator


    【解决方案1】:

    如果您使用的是SensioFrameworkExtraBundle,您可以使用annotate the controller class。从他们的例子中,

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
    
    class PostController extends Controller
    {
        /**
         * @Security("has_role('ROLE_ADMIN')")
         */
        public function indexAction()
        {
            // ...
        }
    }
    

    另一种选择是 JMSSecurityExtraBundlesecure your service layer,例如,

    namespace Acme\HelloBundle\Newsletter;
    
    use JMS\SecurityExtraBundle\Annotation\Secure;
    // ...
    
    class NewsletterManager
    {
    
        /**
         * @Secure(roles="ROLE_NEWSLETTER_ADMIN")
         */
        public function sendNewsletter()
        {
            // ...
        }
    
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-31
      • 2014-10-17
      • 2020-10-21
      • 2013-02-11
      • 2014-01-25
      • 2022-01-11
      • 1970-01-01
      • 2019-06-05
      相关资源
      最近更新 更多