Using role constants with the IsGranted Symfony attribute
Published on 2023-06-06 • Modified on 2023-06-06
This snippet shows how to use role constants with the IsGranted
Symfony attribute instead of using raw strings. We can use the AuthenticatedVoter
class, which contains several predefined constants, as shown below. If you have custom roles, you can put them in your user class, like in the Symfony demo.
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Snippet 259.
*
* @see vendor/symfony/security-core/Authorization/Voter/AuthenticatedVoter.php
*/
final class SecuredController extends AbstractController
{
#[Route(path: '/dummy/secured', name: 'dummy_secured')]
#[IsGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY)]
public function __invoke(): Response
{
return $this->json(['OK' => true]);
}
}
More on Stackoverflow Read the doc More on the web Random snippet