Skip to content

Commit 3a439bd

Browse files
committed
[#14011] Documented the NullToken usage
1 parent ca8621d commit 3a439bd

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

security/experimental_authenticators.rst

+36
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,42 @@ unauthenticated access (e.g. the login page):
135135
],
136136
]);
137137
138+
Granting Anonymous Users Access in a Custom Voter
139+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
140+
141+
.. versionadded:: 5.2
142+
143+
The ``NullToken`` class was introduced in Symfony 5.2.
144+
145+
If you're using a :doc:`custom voter </security/voters>`, you can allow
146+
anonymous users access by checking for a special
147+
:class:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\NullToken`. This token is used
148+
in the voters to represent the unauthenticated access::
149+
150+
// src/Security/PostVoter.php
151+
namespace App\Security;
152+
153+
// ...
154+
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
155+
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
156+
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
157+
158+
class PostVoter extends Voter
159+
{
160+
// ...
161+
162+
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
163+
{
164+
// ...
165+
166+
if ($token instanceof NullToken) {
167+
// the user is not authenticated, e.g. only allow them to
168+
// see public posts
169+
return $subject->isPublic();
170+
}
171+
}
172+
}
173+
138174
.. _authenticators-required-entry-point:
139175

140176
Configuring the Authentication Entry Point

0 commit comments

Comments
 (0)