Skip to content

[Security] Documented the NullToken usage #14551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 16, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions security/experimental_authenticators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 </security/voters>`, 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
Expand Down