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

[Security] Add a method in the security helper to ease programmatic logout #41406

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 3 commits into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[Security] Add a method in the security helper to ease programmatic l…
…ogout (#40663)
  • Loading branch information
johnkrovitch authored and chalasr committed Jul 19, 2022
commit f576173a96ce9409a829b416500649a6857be98a
1 change: 1 addition & 0 deletions 1 src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* Deprecate the `Symfony\Component\Security\Core\Security` service alias, use `Symfony\Bundle\SecurityBundle\Security\Security` instead
* Add `Security::getFirewallConfig()` to help to get the firewall configuration associated to the Request
* Add `Security::login()` to login programmatically
* Add `Security::logout()` to logout programmatically

6.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,13 @@ private function createFirewall(ContainerBuilder $container, string $id, array $
$container->register($firewallEventDispatcherId, EventDispatcher::class)
->addTag('event_dispatcher.dispatcher', ['name' => $firewallEventDispatcherId]);

$eventDispatcherLocator = $container->getDefinition('security.firewall.event_dispatcher_locator');
$eventDispatcherLocator
->replaceArgument(0, array_merge($eventDispatcherLocator->getArgument(0), [
$id => new ServiceClosureArgument(new Reference($firewallEventDispatcherId)),
]))
;

// Register listeners
$listeners = [];
$listenerKeys = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
'request_stack' => service('request_stack'),
'security.firewall.map' => service('security.firewall.map'),
'security.user_checker' => service('security.user_checker'),
'security.firewall.event_dispatcher_locator' => service('security.firewall.event_dispatcher_locator'),
]),
abstract_arg('authenticators'),
])
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\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\Security\Http\AccessMap;
use Symfony\Component\Security\Http\Authentication\CustomAuthenticationFailureHandler;
use Symfony\Component\Security\Http\Authentication\CustomAuthenticationSuccessHandler;
Expand Down Expand Up @@ -160,5 +161,8 @@
service('security.access_map'),
])
->tag('monolog.logger', ['channel' => 'security'])

->set('security.firewall.event_dispatcher_locator', ServiceLocator::class)
->args([[]])
;
};
24 changes: 24 additions & 0 deletions 24 src/Symfony/Bundle/SecurityBundle/Security/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\Security as LegacySecurity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\Service\ServiceProviderInterface;

/**
Expand Down Expand Up @@ -60,6 +62,28 @@ public function login(UserInterface $user, string $authenticatorName = null, str
$this->container->get('security.user_authenticator')->authenticateUser($user, $authenticator, $request);
}

/**
* Logout the current user by dispatching the LogoutEvent.
*
* @return Response|null The LogoutEvent's Response if any
*/
public function logout(): ?Response
{
$request = $this->container->get('request_stack')->getMainRequest();
$logoutEvent = new LogoutEvent($request, $this->container->get('security.token_storage')->getToken());
$firewallConfig = $this->container->get('security.firewall.map')->getFirewallConfig($request);

if (!$firewallConfig) {
throw new LogicException('It is not possible to logout, as the request is not behind a firewall.');
}
$firewallName = $firewallConfig->getName();

$this->container->get('security.firewall.event_dispatcher_locator')->get($firewallName)->dispatch($logoutEvent);
$this->container->get('security.token_storage')->setToken();

return $logoutEvent->getResponse();
}

private function getAuthenticator(?string $authenticatorName, string $firewallName): AuthenticatorInterface
{
if (!\array_key_exists($firewallName, $this->authenticators)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,24 @@ public function testLoginWithBuiltInAuthenticator(string $authenticator)
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(['message' => 'Welcome @chalasr!'], json_decode($response->getContent(), true));
}

/**
* @testWith ["json_login"]
* ["Symfony\\Bundle\\SecurityBundle\\Tests\\Functional\\Bundle\\AuthenticatorBundle\\ApiAuthenticator"]
*/
public function testLogout(string $authenticator)
{
$client = $this->createClient(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml', 'debug' => true]);
static::getContainer()->get(WelcomeController::class)->authenticator = $authenticator;
$client->request('GET', '/welcome');
$this->assertEquals('chalasr', static::getContainer()->get('security.helper')->getUser()->getUserIdentifier());

$client->request('GET', '/auto-logout');
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$this->assertNull(static::getContainer()->get('security.helper')->getUser());
$this->assertSame(['message' => 'Logout successful'], json_decode($response->getContent(), true));
}
}

final class UserWithoutEquatable implements UserInterface, PasswordAuthenticatedUserInterface
Expand Down Expand Up @@ -224,3 +242,17 @@ public function welcome()
return new JsonResponse(['message' => sprintf('Welcome @%s!', $this->security->getUser()->getUserIdentifier())]);
}
}

class LogoutController
{
public function __construct(private Security $security)
{
}

public function logout()
{
$this->security->logout();

return new JsonResponse(['message' => 'Logout successful']);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ services:
arguments: ['@security.helper']
public: true

Symfony\Bundle\SecurityBundle\Tests\Functional\LogoutController:
arguments: ['@security.helper']
public: true

Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ApiAuthenticator: ~

security:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
welcome:
path: /welcome
defaults: { _controller: Symfony\Bundle\SecurityBundle\Tests\Functional\WelcomeController::welcome }
controller: Symfony\Bundle\SecurityBundle\Tests\Functional\WelcomeController::welcome

logout:
path: /auto-logout
controller: Symfony\Bundle\SecurityBundle\Tests\Functional\LogoutController::logout
180 changes: 179 additions & 1 deletion 180 src/Symfony/Bundle/SecurityBundle/Tests/Security/SecurityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Service\ServiceProviderInterface;

class SecurityTest extends TestCase
Expand Down Expand Up @@ -117,7 +121,7 @@ public function getFirewallConfigTests()
yield [$request, new FirewallConfig('main', 'acme_user_checker')];
}

public function testAutoLogin()
public function testLogin()
{
$request = new Request();
$authenticator = $this->createMock(AuthenticatorInterface::class);
Expand Down Expand Up @@ -163,6 +167,180 @@ public function testAutoLogin()
$security->login($user);
}

public function testLogout()
{
$request = new Request();
$requestStack = $this->createMock(RequestStack::class);
$requestStack
->expects($this->once())
->method('getMainRequest')
->willReturn($request)
;

$token = $this->createMock(TokenInterface::class);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn($token)
;
$tokenStorage
->expects($this->once())
->method('setToken')
;

$eventDispatcher = $this->createMock(EventDispatcherInterface::class);
$eventDispatcher
->expects($this->once())
->method('dispatch')
->with(new LogoutEvent($request, $token))
;

$firewallMap = $this->createMock(FirewallMap::class);
$firewallConfig = new FirewallConfig('my_firewall', 'user_checker');
$firewallMap
->expects($this->once())
->method('getFirewallConfig')
->willReturn($firewallConfig)
;

$eventDispatcherLocator = $this->createMock(ContainerInterface::class);
$eventDispatcherLocator
->expects($this->atLeastOnce())
->method('get')
->willReturnMap([
['my_firewall', $eventDispatcher],
])
;

$container = $this->createMock(ContainerInterface::class);
$container
->expects($this->atLeastOnce())
->method('get')
->willReturnMap([
['request_stack', $requestStack],
['security.token_storage', $tokenStorage],
['security.firewall.map', $firewallMap],
['security.firewall.event_dispatcher_locator', $eventDispatcherLocator],
])
;
$security = new Security($container);
$security->logout();
}

public function testLogoutWithoutFirewall()
{
$request = new Request();
$requestStack = $this->createMock(RequestStack::class);
$requestStack
->expects($this->once())
->method('getMainRequest')
->willReturn($request)
;

$token = $this->createMock(TokenInterface::class);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn($token)
;

$firewallMap = $this->createMock(FirewallMap::class);
$firewallMap
->expects($this->once())
->method('getFirewallConfig')
->willReturn(null)
;

$container = $this->createMock(ContainerInterface::class);
$container
->expects($this->atLeastOnce())
->method('get')
->willReturnMap([
['request_stack', $requestStack],
['security.token_storage', $tokenStorage],
['security.firewall.map', $firewallMap],
])
;

$this->expectException(LogicException::class);
$security = new Security($container);
$security->logout();
}

public function testLogoutWithResponse()
{
$request = new Request();
$requestStack = $this->createMock(RequestStack::class);
$requestStack
->expects($this->once())
->method('getMainRequest')
->willReturn($request)
;

$token = $this->createMock(TokenInterface::class);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn($token)
;
$tokenStorage
->expects($this->once())
->method('setToken')
;

$eventDispatcher = $this->createMock(EventDispatcherInterface::class);
$eventDispatcher
->expects($this->once())
->method('dispatch')
->willReturnCallback(function ($event) use ($request, $token) {
$this->assertInstanceOf(LogoutEvent::class, $event);
$this->assertEquals($request, $event->getRequest());
$this->assertEquals($token, $event->getToken());

$event->setResponse(new Response('a custom response'));

return $event;
})
;

$firewallMap = $this->createMock(FirewallMap::class);
$firewallConfig = new FirewallConfig('my_firewall', 'user_checker');
$firewallMap
->expects($this->once())
->method('getFirewallConfig')
->willReturn($firewallConfig)
;

$eventDispatcherLocator = $this->createMock(ContainerInterface::class);
$eventDispatcherLocator
->expects($this->atLeastOnce())
->method('get')
->willReturnMap([
['my_firewall', $eventDispatcher],
])
;

$container = $this->createMock(ContainerInterface::class);
$container
->expects($this->atLeastOnce())
->method('get')
->willReturnMap([
['request_stack', $requestStack],
['security.token_storage', $tokenStorage],
['security.firewall.map', $firewallMap],
['security.firewall.event_dispatcher_locator', $eventDispatcherLocator],
])
;
$security = new Security($container);
$response = $security->logout();

$this->assertInstanceOf(Response::class, $response);
$this->assertEquals('a custom response', $response->getContent());
}

private function createContainer(string $serviceId, object $serviceObject): ContainerInterface
{
return new ServiceLocator([$serviceId => fn () => $serviceObject]);
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.