From 3a439bddc1646c482f3f6f78894391c0153199da Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Mon, 16 Nov 2020 00:02:25 +0100 Subject: [PATCH] [#14011] Documented the NullToken usage --- security/experimental_authenticators.rst | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/security/experimental_authenticators.rst b/security/experimental_authenticators.rst index d0813795b12..45c0edb882d 100644 --- a/security/experimental_authenticators.rst +++ b/security/experimental_authenticators.rst @@ -135,6 +135,42 @@ unauthenticated access (e.g. the login page): ], ]); +Granting Anonymous Users Access in a Custom Voter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 5.2 + + The ``NullToken`` class was introduced in Symfony 5.2. + +If you're using a :doc:`custom voter `, you can allow +anonymous users access by checking for a special +:class:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\NullToken`. This token is used +in the voters to represent the unauthenticated access:: + + // src/Security/PostVoter.php + namespace App\Security; + + // ... + use Symfony\Component\Security\Core\Authentication\Token\NullToken; + use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; + use Symfony\Component\Security\Core\Authorization\Voter\Voter; + + class PostVoter extends Voter + { + // ... + + protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool + { + // ... + + if ($token instanceof NullToken) { + // the user is not authenticated, e.g. only allow them to + // see public posts + return $subject->isPublic(); + } + } + } + .. _authenticators-required-entry-point: Configuring the Authentication Entry Point