简体   繁体   English

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

[英]Protect a Symfony2 Controller's action from unauthorized requests with an Annotation

I can't seem to find out if it is possible to protect a Controller's Action when the user is not logged in using a Custom Annotation . 当用户未使用Custom Annotation登录时,我似乎无法发现是否可以保护Controller's Action

This is what I want to achieve: 这是我要实现的目标:

...
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
    }

    ...
}

I know I could do this using some sort of " Decorator Design Pattern " but what I'd really want is something more like Python 's Decorator using PHP Annotations 我知道我可以使用某种“ 装饰器设计模式 ”来做到这一点,但我真正想要的是更类似于Python使用PHP 注释装饰器

Is this posible? 这可能吗? How would I do it? 我该怎么办?

If you're using the SensioFrameworkExtraBundle you can annotate the controller class . 如果您使用的是SensioFrameworkExtraBundle ,则可以注释控制器类 From their example, 从他们的例子来看

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

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

Another alternative is the JMSSecurityExtraBundle to secure your service layer , eg, 另一个替代方法是JMSSecurityExtraBundle,保护您的服务层 ,例如,

namespace Acme\HelloBundle\Newsletter;

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

class NewsletterManager
{

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

    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM