Skip to content

[Security] Add FirewallUserAuthenticator - authenticate users in any firewall #39346

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,9 @@ private function createFirewalls(array $config, ContainerBuilder $container)

// load firewall map
$mapDef = $container->getDefinition('security.firewall.map');
if ($this->authenticatorManagerEnabled = $config['enable_authenticator_manager']) {
$firewallUserAuthenticatorDef = $container->getDefinition('security.firewall_user_authenticator');
}
$map = $authenticationProviders = $contextRefs = [];
foreach ($firewalls as $name => $firewall) {
if (isset($firewall['user_checker']) && 'security.user_checker' !== $firewall['user_checker']) {
Expand All @@ -292,6 +295,9 @@ private function createFirewalls(array $config, ContainerBuilder $container)
}
$mapDef->replaceArgument(0, ServiceLocatorTagPass::register($container, $contextRefs));
$mapDef->replaceArgument(1, new IteratorArgument($map));
if ($this->authenticatorManagerEnabled = $config['enable_authenticator_manager']) {
$firewallUserAuthenticatorDef->replaceArgument(0, ServiceLocatorTagPass::register($container, $contextRefs));
}

if (!$this->authenticatorManagerEnabled) {
// add authentication providers to authentication manager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bundle\SecurityBundle\Security\FirewallUserAuthenticator;
use Symfony\Bundle\SecurityBundle\Security\UserAuthenticator;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
Expand Down Expand Up @@ -60,6 +61,13 @@
])
->alias(UserAuthenticatorInterface::class, 'security.user_authenticator')

->set('security.firewall_user_authenticator', FirewallUserAuthenticator::class)
->args([
abstract_arg('Firewall context locator'),
service('event_dispatcher'),
])
->alias(FirewallUserAuthenticator::class, 'security.firewall_user_authenticator')

->set('security.authentication.manager', NoopAuthenticationManager::class)
->alias(AuthenticationManagerInterface::class, 'security.authentication.manager')

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Security;

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\BadgeInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Event\AuthenticationTokenCreatedEvent;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
* @author Martin Kirilov <wucdbm@gmail.com>
*
* @final
* @experimental in 5.2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this should be introduced as experimental, it needs to target 6.0 please

*/
class FirewallUserAuthenticator
{
private $firewallLocator;
private $eventDispatcher;

public function __construct(ContainerInterface $firewallLocator, EventDispatcherInterface $eventDispatcher)
{
$this->firewallLocator = $firewallLocator;
$this->eventDispatcher = $eventDispatcher;
}

/**
* @param BadgeInterface[] $badges Optionally, pass some Passport badges to use for the manual login
*/
public function authenticateUser(UserInterface $user, Request $request, string $firewallName, array $badges = []): void
{
// TODO Tests
// TODO Throw if not master request?
if (!$request->hasSession()) {
return;
}

if (!$this->firewallLocator->has('security.firewall.map.context.'.$firewallName)) {
throw new \LogicException(sprintf('Firewall "%s" not found. Did you register your firewall?', $firewallName));
}

/** @var FirewallContext $firewallContext */
$firewallContext = $this->firewallLocator->get('security.firewall.map.context.'.$firewallName);
// todo can firewall config ever be null?
$firewallConfig = $firewallContext->getConfig();

// Note: We're only using PreAuthenticatedAuthenticator because of Symfony\Component\Security\Http\EventListener\RememberMeListener
$authenticator = new PreAuthenticatedAuthenticator();
// create PreAuthenticatedToken token for the User
$token = $authenticator->createAuthenticatedToken($passport = new SelfValidatingPassport(new UserBadge($user->getUsername(), function () use ($user) { return $user; }), $badges), $firewallName);

// announce the authenticated token
$token = $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($token))->getAuthenticatedToken();

$this->eventDispatcher->dispatch($loginSuccessEvent = new LoginSuccessEvent($authenticator, $passport, $token, $request, null, $firewallName));

$sessionKey = '_security_'.$firewallConfig->getContext();
$session = $request->getSession();
// increments the internal session usage index
$session->getMetadataBag();
$session->set($sessionKey, serialize($token));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
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\PassportInterface;

/**
* This class is only used in FirewallUserAuthenticator.
* Its sole reason if existence is LoginSuccessEvent requiring an authenticator.
*
* @author Martin Kirilov <wucdbm@gmail.com>
*
* @internal
*
* @experimental in 5.2
*/
class PreAuthenticatedAuthenticator implements AuthenticatorInterface
{
public function supports(Request $request): ?bool
{
return true;
}

public function authenticate(Request $request): PassportInterface
{
throw new \LogicException(sprintf('"%s" does not support "%s::authenticate()" calls.', static::class, AuthenticatorInterface::class));
}

public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
{
// TODO Tests
return new PreAuthenticatedToken($passport->getUser(), null, $firewallName, $passport->getUser()->getRoles());
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return null;
}
}