Skip to content

Commit 34a9498

Browse files
committed
feature #35997 [DX][Testing] Added a loginUser() method to test protected resources (javiereguiluz, wouterj)
This PR was merged into the 5.1-dev branch. Discussion ---------- [DX][Testing] Added a loginUser() method to test protected resources | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | Deprecations? | no | Tickets | Fix #26839 | License | MIT | Doc PR | tbd This finishes symfony/symfony#32850 original description: > I know this won't work for 100% of our users ... but the goal is to make life easier to *most* of them. Thanks! A custom `ConcreteToken` test-object is created as suggested by @linaori, to not bind this token to any specific implementation (as other implementations aren't fully compatible with eachother). Commits ------- 2980a680d4 Added special test token and implemented 'real' functional tests f516829d99 [DX][Testing] Added a loginUser() method to test protected resources
2 parents 7686b8f + fecfeb4 commit 34a9498

File tree

8 files changed

+217
-0
lines changed

8 files changed

+217
-0
lines changed

KernelBrowser.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace Symfony\Bundle\FrameworkBundle;
1313

14+
use Symfony\Bundle\FrameworkBundle\Test\TestBrowserToken;
15+
use Symfony\Component\BrowserKit\Cookie;
1416
use Symfony\Component\BrowserKit\CookieJar;
1517
use Symfony\Component\BrowserKit\History;
1618
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -19,6 +21,7 @@
1921
use Symfony\Component\HttpKernel\HttpKernelBrowser;
2022
use Symfony\Component\HttpKernel\KernelInterface;
2123
use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile;
24+
use Symfony\Component\Security\Core\User\UserInterface;
2225

2326
/**
2427
* Simulates a browser and makes requests to a Kernel object.
@@ -104,6 +107,31 @@ public function enableReboot()
104107
$this->reboot = true;
105108
}
106109

110+
/**
111+
* @param UserInterface $user
112+
*/
113+
public function loginUser($user, string $firewallContext = 'main'): self
114+
{
115+
if (!interface_exists(UserInterface::class)) {
116+
throw new \LogicException(sprintf('"%s" requires symfony/security-core to be installed.', __METHOD__));
117+
}
118+
119+
if (!$user instanceof UserInterface) {
120+
throw new \LogicException(sprintf('The first argument of "%s" must be instance of "%s", "%s" provided.', __METHOD__, UserInterface::class, \is_object($user) ? \get_class($user) : \gettype($user)));
121+
}
122+
123+
$token = new TestBrowserToken($user->getRoles(), $user);
124+
$token->setAuthenticated(true);
125+
$session = $this->getContainer()->get('session');
126+
$session->set('_security_'.$firewallContext, serialize($token));
127+
$session->save();
128+
129+
$cookie = new Cookie($session->getName(), $session->getId());
130+
$this->getCookieJar()->set($cookie);
131+
132+
return $this;
133+
}
134+
107135
/**
108136
* {@inheritdoc}
109137
*

Test/TestBrowserToken.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bundle\FrameworkBundle\Test;
13+
14+
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
15+
use Symfony\Component\Security\Core\User\UserInterface;
16+
17+
/**
18+
* A very limited token that is used to login in tests using the KernelBrowser.
19+
*
20+
* @author Wouter de Jong <[email protected]>
21+
*/
22+
class TestBrowserToken extends AbstractToken
23+
{
24+
public function __construct(array $roles = [], UserInterface $user = null)
25+
{
26+
parent::__construct($roles);
27+
28+
if (null !== $user) {
29+
$this->setUser($user);
30+
}
31+
}
32+
33+
public function getCredentials()
34+
{
35+
return null;
36+
}
37+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;
13+
14+
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
15+
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
16+
use Symfony\Component\HttpFoundation\Response;
17+
18+
class SecurityController implements ContainerAwareInterface
19+
{
20+
use ContainerAwareTrait;
21+
22+
public function profileAction()
23+
{
24+
return new Response('Welcome '.$this->container->get('security.token_storage')->getToken()->getUsername().'!');
25+
}
26+
}

Tests/Functional/SecurityTest.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
13+
14+
use Symfony\Component\Security\Core\User\User;
15+
16+
class SecurityTest extends AbstractWebTestCase
17+
{
18+
/**
19+
* @dataProvider getUsers
20+
*/
21+
public function testLoginUser(string $username, array $roles, ?string $firewallContext)
22+
{
23+
$user = new User($username, 'the-password', $roles);
24+
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
25+
26+
if (null === $firewallContext) {
27+
$client->loginUser($user);
28+
} else {
29+
$client->loginUser($user, $firewallContext);
30+
}
31+
32+
$client->request('GET', '/'.($firewallContext ?? 'main').'/user_profile');
33+
$this->assertEquals('Welcome '.$username.'!', $client->getResponse()->getContent());
34+
}
35+
36+
public function getUsers()
37+
{
38+
yield ['the-username', ['ROLE_FOO'], null];
39+
yield ['the-username', ['ROLE_FOO'], 'main'];
40+
yield ['other-username', ['ROLE_FOO'], 'custom'];
41+
42+
yield ['the-username', ['ROLE_FOO'], null];
43+
yield ['no-role-username', [], null];
44+
}
45+
46+
public function testLoginUserMultipleRequests()
47+
{
48+
$user = new User('the-username', 'the-password', ['ROLE_FOO']);
49+
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
50+
$client->loginUser($user);
51+
52+
$client->request('GET', '/main/user_profile');
53+
$this->assertEquals('Welcome the-username!', $client->getResponse()->getContent());
54+
55+
$client->request('GET', '/main/user_profile');
56+
$this->assertEquals('Welcome the-username!', $client->getResponse()->getContent());
57+
}
58+
59+
public function testLoginInBetweenRequests()
60+
{
61+
$user = new User('the-username', 'the-password', ['ROLE_FOO']);
62+
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
63+
64+
$client->request('GET', '/main/user_profile');
65+
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
66+
67+
$client->loginUser($user);
68+
69+
$client->request('GET', '/main/user_profile');
70+
$this->assertEquals('Welcome the-username!', $client->getResponse()->getContent());
71+
}
72+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
13+
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle;
14+
use Symfony\Bundle\SecurityBundle\SecurityBundle;
15+
16+
return [
17+
new FrameworkBundle(),
18+
new SecurityBundle(),
19+
new TestBundle(),
20+
];
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
imports:
2+
- { resource: ./../config/default.yml }
3+
4+
security:
5+
providers:
6+
main:
7+
memory:
8+
users:
9+
the-username: { password: the-password, roles: ['ROLE_FOO'] }
10+
no-role-username: { password: the-password, roles: [] }
11+
custom:
12+
memory:
13+
users:
14+
other-username: { password: the-password, roles: ['ROLE_FOO'] }
15+
16+
firewalls:
17+
main:
18+
pattern: ^/main
19+
form_login:
20+
check_path: /main/login/check
21+
provider: main
22+
custom:
23+
pattern: ^/custom
24+
form_login:
25+
check_path: /custom/login/check
26+
provider: custom
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
security_profile:
2+
path: /main/user_profile
3+
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\SecurityController::profileAction }
4+
5+
security_custom_profile:
6+
path: /custom/user_profile
7+
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\SecurityController::profileAction }

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"symfony/messenger": "^4.4|^5.0",
4848
"symfony/mime": "^4.4|^5.0",
4949
"symfony/process": "^4.4|^5.0",
50+
"symfony/security-bundle": "^5.1",
5051
"symfony/security-csrf": "^4.4|^5.0",
5152
"symfony/security-http": "^4.4|^5.0",
5253
"symfony/serializer": "^4.4|^5.0",

0 commit comments

Comments
 (0)