Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Created July 8, 2020 13:02
Show Gist options
  • Save romaricdrigon/63f1d83ba7c516e6c6205b384c18376f to your computer and use it in GitHub Desktop.
Save romaricdrigon/63f1d83ba7c516e6c6205b384c18376f to your computer and use it in GitHub Desktop.
<?php
namespace App\User\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\AnonymousPassport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
/**
* Some of our Voters are voting against anonymous Users ;
* new system doe not support Anonymous tokens anymore, so we added this authenticator to keep BC.
*
* Related issue: https://github.com/symfony/symfony/issues/37523
*/
class AnonymousAuthenticator implements AuthenticatorInterface
{
private string $secret;
private TokenStorageInterface $tokenStorage;
public function __construct(string $secret, TokenStorageInterface $tokenStorage)
{
$this->secret = $secret;
$this->tokenStorage = $tokenStorage;
}
public function supports(Request $request): ?bool
{
// Do not re-authentify an anonymous User if we already have someone
if ($this->tokenStorage->getToken()) {
return false;
}
return true;
}
public function authenticate(Request $request): PassportInterface
{
return new AnonymousPassport();
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null; // Noting to do
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return null; // Failure is not an option
}
public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
{
return new AnonymousToken($this->secret, 'anon.');
}
}
security:
# Use the new Security component - experimental in 5.1
# https://symfony.com/blog/new-in-symfony-5-1-updated-security-system
enable_authenticator_manager: true
# ...
firewalls:
main:
custom_authenticators:
- App\User\Security\LoginFormAuthenticator
- App\User\Security\AnonymousAuthenticator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment