Search code examples
phpsymfonysymfony5symfony-securityphp-8

Symfony 5 PHP8 Attributes for Security


I have a page that I am trying to convert from annotations to PHP8 attributes.

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[IsGranted('ROLE_ADMIN')]
#[Route('/page')]
class PageController extends AbstractController
{
    #[Route('/', name: 'page')]
    public function index(): Response
    {
        return $this->render('page/index.html.twig', [
            'controller_name' => 'PageController',
        ]);
    }
}

The IsGranted attribute doesn't seem to work, as the page is accessible instead of a 403 error. On the other hand when converted to annotations, like below it works as expected. Is there a config setting I am missing?

/**
 * @IsGranted("ROLE_ADMIN")
 */
#[Route('/page')]
class PageController extends AbstractController
{
    #[Route('/', name: 'page')]
    public function index(): Response
    {
        return $this->render('page/index.html.twig', [
            'controller_name' => 'PageController',
        ]);
    }
}

Other attributes eg #[Route], #[Entity] etc works, but the Security attributes do not seem to work.


Solution

  • Support for PHP8 attributes in the SensioFrameworkExtraBundle package are available only from version 6.1.0. You likely just need to update it.