Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit b02ef09

Browse filesBrowse files
committed
[Security] Add a method in the security helper to ease programmatic login (#40662)
1 parent 27b1654 commit b02ef09
Copy full SHA for b02ef09

File tree

4 files changed

+152
-12
lines changed
Filter options

4 files changed

+152
-12
lines changed

‎src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php
+17-4Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -293,16 +293,25 @@ private function createFirewalls(array $config, ContainerBuilder $container)
293293

294294
// load firewall map
295295
$mapDef = $container->getDefinition('security.firewall.map');
296-
$map = $authenticationProviders = $contextRefs = [];
296+
$map = $authenticationProviders = $contextRefs = $authenticators = [];
297297
foreach ($firewalls as $name => $firewall) {
298298
if (isset($firewall['user_checker']) && 'security.user_checker' !== $firewall['user_checker']) {
299299
$customUserChecker = true;
300300
}
301301

302302
$configId = 'security.firewall.map.config.'.$name;
303303

304-
[$matcher, $listeners, $exceptionListener, $logoutListener] = $this->createFirewall($container, $name, $firewall, $authenticationProviders, $providerIds, $configId);
304+
[$matcher, $listeners, $exceptionListener, $logoutListener, $firewallAuthenticators] = $this->createFirewall($container, $name, $firewall, $authenticationProviders, $providerIds, $configId);
305305

306+
if (!$firewallAuthenticators) {
307+
$authenticators[$name] = null;
308+
} else {
309+
$firewallAuthenticatorRefs = [];
310+
foreach ($firewallAuthenticators as $authenticatorId) {
311+
$firewallAuthenticatorRefs[$authenticatorId] = new Reference($authenticatorId);
312+
}
313+
$authenticators[$name] = ServiceLocatorTagPass::register($container, $firewallAuthenticatorRefs);
314+
}
306315
$contextId = 'security.firewall.map.context.'.$name;
307316
$isLazy = !$firewall['stateless'] && (!empty($firewall['anonymous']['lazy']) || $firewall['lazy']);
308317
$context = new ChildDefinition($isLazy ? 'security.firewall.lazy_context' : 'security.firewall.context');
@@ -317,6 +326,10 @@ private function createFirewalls(array $config, ContainerBuilder $container)
317326
$contextRefs[$contextId] = new Reference($contextId);
318327
$map[$contextId] = $matcher;
319328
}
329+
$container
330+
->getDefinition('security.helper')
331+
->replaceArgument(1, $authenticators)
332+
;
320333

321334
$container->setAlias('security.firewall.context_locator', (string) ServiceLocatorTagPass::register($container, $contextRefs));
322335

@@ -362,7 +375,7 @@ private function createFirewall(ContainerBuilder $container, string $id, array $
362375

363376
// Security disabled?
364377
if (false === $firewall['security']) {
365-
return [$matcher, [], null, null];
378+
return [$matcher, [], null, null, []];
366379
}
367380

368381
$config->replaceArgument(4, $firewall['stateless']);
@@ -565,7 +578,7 @@ private function createFirewall(ContainerBuilder $container, string $id, array $
565578
$config->replaceArgument(10, $listenerKeys);
566579
$config->replaceArgument(11, $firewall['switch_user'] ?? null);
567580

568-
return [$matcher, $listeners, $exceptionListener, null !== $logoutListenerId ? new Reference($logoutListenerId) : null];
581+
return [$matcher, $listeners, $exceptionListener, null !== $logoutListenerId ? new Reference($logoutListenerId) : null, $firewallAuthenticationProviders];
569582
}
570583

571584
private function createContextListener(ContainerBuilder $container, string $contextKey, ?string $firewallEventDispatcherId)

‎src/Symfony/Bundle/SecurityBundle/Resources/config/security.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/SecurityBundle/Resources/config/security.php
+11-4Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,17 @@
8787
->set('security.untracked_token_storage', TokenStorage::class)
8888

8989
->set('security.helper', Security::class)
90-
->args([service_locator([
91-
'security.token_storage' => service('security.token_storage'),
92-
'security.authorization_checker' => service('security.authorization_checker'),
93-
])])
90+
->args([
91+
service_locator([
92+
'security.token_storage' => service('security.token_storage'),
93+
'security.authorization_checker' => service('security.authorization_checker'),
94+
'security.user_authenticator' => service('security.user_authenticator')->ignoreOnInvalid(),
95+
'request_stack' => service('request_stack'),
96+
'security.firewall.map' => service('security.firewall.map'),
97+
'security.user_checker' => service('security.user_checker'),
98+
]),
99+
abstract_arg('authenticators'),
100+
])
94101
->alias(Security::class, 'security.helper')
95102

96103
->set('security.user_value_resolver', UserValueResolver::class)

‎src/Symfony/Component/Security/Core/Security.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Security/Core/Security.php
+45-1Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
use Psr\Container\ContainerInterface;
1515
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
1616
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
17+
use Symfony\Component\Security\Core\Exception\LogicException;
1718
use Symfony\Component\Security\Core\User\UserInterface;
19+
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
20+
use Symfony\Contracts\Service\ServiceProviderInterface;
1821

1922
/**
2023
* Helper class for commonly-needed security tasks.
@@ -30,9 +33,15 @@ class Security implements AuthorizationCheckerInterface
3033

3134
private $container;
3235

33-
public function __construct(ContainerInterface $container)
36+
/**
37+
* @param array<string, ServiceProviderInterface> $authenticators An array of authenticator service locator indexed by firewall name
38+
*/
39+
private $authenticators;
40+
41+
public function __construct(ContainerInterface $container, array $authenticators = [])
3442
{
3543
$this->container = $container;
44+
$this->authenticators = $authenticators;
3645
}
3746

3847
public function getUser(): ?UserInterface
@@ -69,4 +78,39 @@ public function getToken(): ?TokenInterface
6978
{
7079
return $this->container->get('security.token_storage')->getToken();
7180
}
81+
82+
public function autoLogin(UserInterface $user, AuthenticatorInterface $authenticator = null, string $firewallName = null): void
83+
{
84+
$request = $this->container->get('request_stack')->getCurrentRequest();
85+
86+
if (null === $authenticator) {
87+
if (null === $firewallName) {
88+
$firewall = $this->container->get('security.firewall.map')->getFirewallConfig($request);
89+
90+
if (null === $firewall) {
91+
throw new LogicException('No firewall found as the current route is not covered by any firewall.');
92+
}
93+
$firewallName = $firewall->getName();
94+
}
95+
96+
if (!isset($firewallName, $this->authenticators)) {
97+
throw new LogicException(sprintf('No authenticators found for firewall "%s".', $firewallName));
98+
}
99+
100+
/** @var ServiceProviderInterface $firewallAuthenticatorLocator */
101+
$firewallAuthenticatorLocator = $this->authenticators[$firewallName];
102+
$authenticatorIds = array_keys($firewallAuthenticatorLocator->getProvidedServices());
103+
104+
if (!$authenticatorIds) {
105+
throw new LogicException('No authenticator was found for the firewall "%s".');
106+
}
107+
108+
if (1 < \count($authenticatorIds)) {
109+
throw new LogicException(sprintf('Too much authenticators were found for the current firewall "%s". You must provide an instance of "%s" to allow an auto login. The available authenticators for the firewall "%s" are "%s".', $firewallName, AuthenticatorInterface::class, $firewallName, implode('" ,"', $authenticatorIds)));
110+
}
111+
$authenticator = $firewallAuthenticatorLocator->get($authenticatorIds[0]);
112+
}
113+
$this->container->get('security.user_checker')->checkPreAuth($user);
114+
$this->container->get('security.user_authenticator')->authenticateUser($user, $authenticator, $request);
115+
}
72116
}

‎src/Symfony/Component/Security/Core/Tests/SecurityTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Security/Core/Tests/SecurityTest.php
+79-3Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,21 @@
1313

1414
use PHPUnit\Framework\TestCase;
1515
use Psr\Container\ContainerInterface;
16+
use Symfony\Bundle\SecurityBundle\Security\FirewallConfig;
17+
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
18+
use Symfony\Component\HttpFoundation\Request;
19+
use Symfony\Component\HttpFoundation\RequestStack;
1620
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
1721
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
1822
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
1923
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
2024
use Symfony\Component\Security\Core\Security;
2125
use Symfony\Component\Security\Core\User\InMemoryUser;
26+
use Symfony\Component\Security\Core\User\UserCheckerInterface;
27+
use Symfony\Component\Security\Core\User\UserInterface;
28+
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
29+
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
30+
use Symfony\Contracts\Service\ServiceProviderInterface;
2231

2332
class SecurityTest extends TestCase
2433
{
@@ -33,7 +42,7 @@ public function testGetToken()
3342

3443
$container = $this->createContainer('security.token_storage', $tokenStorage);
3544

36-
$security = new Security($container);
45+
$security = new Security($container, []);
3746
$this->assertSame($token, $security->getToken());
3847
}
3948

@@ -54,7 +63,7 @@ public function testGetUser($userInToken, $expectedUser)
5463

5564
$container = $this->createContainer('security.token_storage', $tokenStorage);
5665

57-
$security = new Security($container);
66+
$security = new Security($container, []);
5867
$this->assertSame($expectedUser, $security->getUser());
5968
}
6069

@@ -81,10 +90,77 @@ public function testIsGranted()
8190

8291
$container = $this->createContainer('security.authorization_checker', $authorizationChecker);
8392

84-
$security = new Security($container);
93+
$security = new Security($container, []);
8594
$this->assertTrue($security->isGranted('SOME_ATTRIBUTE', 'SOME_SUBJECT'));
8695
}
8796

97+
public function testAutoLogin()
98+
{
99+
$request = new Request();
100+
$authenticator = $this->createMock(AuthenticatorInterface::class);
101+
$requestStack = $this->createMock(RequestStack::class);
102+
$firewallMap = $this->createMock(FirewallMap::class);
103+
$firewall = new FirewallConfig('main', 'main');
104+
$userAuthenticator = $this->createMock(UserAuthenticatorInterface::class);
105+
$user = $this->createMock(UserInterface::class);
106+
$userChecker = $this->createMock(UserCheckerInterface::class);
107+
108+
$container = $this->createMock(ContainerInterface::class);
109+
$container
110+
->expects($this->atLeastOnce())
111+
->method('get')
112+
->willReturnMap([
113+
['request_stack', $requestStack],
114+
['security.firewall.map', $firewallMap],
115+
['security.user_authenticator', $userAuthenticator],
116+
['security.user_checker', $userChecker],
117+
])
118+
;
119+
120+
$requestStack
121+
->expects($this->once())
122+
->method('getCurrentRequest')
123+
->willReturn($request)
124+
;
125+
126+
$firewallMap
127+
->expects($this->once())
128+
->method('getFirewallConfig')
129+
->willReturn($firewall)
130+
;
131+
$userAuthenticator
132+
->expects($this->once())
133+
->method('authenticateUser')
134+
->with($user, $authenticator, $request)
135+
;
136+
$userChecker
137+
->expects($this->once())
138+
->method('checkPreAuth')
139+
->with($user)
140+
;
141+
142+
$firewallAuthenticatorLocator = $this->createMock(ServiceProviderInterface::class);
143+
$firewallAuthenticatorLocator
144+
->expects($this->once())
145+
->method('getProvidedServices')
146+
->willReturn([
147+
'security.authenticator.custom.dev' => $authenticator,
148+
])
149+
;
150+
$firewallAuthenticatorLocator
151+
->expects($this->once())
152+
->method('get')
153+
->with('security.authenticator.custom.dev')
154+
->willReturn($authenticator)
155+
;
156+
157+
$security = new Security($container, [
158+
'main' => $firewallAuthenticatorLocator,
159+
]);
160+
161+
$security->autoLogin($user);
162+
}
163+
88164
private function createContainer($serviceId, $serviceObject)
89165
{
90166
$container = $this->createMock(ContainerInterface::class);

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.