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
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉