Closed
Description
Symfony version(s) affected
5.4.*
Description
When using voters and accessing the user through TokenInterface
and there is no user logged in, the function returns an empty string ''
instead of null
. Failing a strict comparison test null === $user
.
How to reproduce
<?php
declare(strict_types=1);
namespace App\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class AuthenticationVoter implements CacheableVoterInterface
{
public function supportsAttribute(string $attribute): bool
{
return \in_array($attribute, [
'IS_AUTHENTICATED_NOT',
], true);
}
public function supportsType(string $subjectType): bool
{
return 'null' === $subjectType;
}
public function vote(TokenInterface $token, $subject, array $attributes): int
{
\assert(null === $subject);
$vote = VoterInterface::ACCESS_ABSTAIN;
$user = $token->getUser();
foreach ($attributes as $attr) {
if ($attr !== 'IS_AUTHENTICATED_NOT') continue;
$vote = VoterInterface::ACCESS_DENIED;
if (null === $user) return VoterInterface::ACCESS_GRANTED;
}
return $vote;
}
}
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Security;
class LoginController
{
#[Route('/sign-in')]
public function signIn(Request $request, Security $security): Response
{
if ($security->isGranted('IS_AUTHENTICATED_NOT')) {
return new Response('Login');
}
return new Response('Only logged out users can login.');
}
}
Possible Solution
No response
Additional Context
No response