File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -135,6 +135,42 @@ unauthenticated access (e.g. the login page):
135
135
],
136
136
]);
137
137
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
+
138
174
.. _authenticators-required-entry-point :
139
175
140
176
Configuring the Authentication Entry Point
You can’t perform that action at this time.
0 commit comments