Skip to content

Commit a946faa

Browse files
Sydney-o9javiereguiluz
authored andcommitted
doc(testing/http_authentication.rst);
- [x] Added notes for people using Guard with the PostAuthenticationGuardToken
1 parent 922577a commit a946faa

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

testing/http_authentication.rst

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,64 @@ needs::
126126
$this->client->getCookieJar()->set($cookie);
127127
}
128128
}
129+
130+
Note: Are you using Guard? You may adjust the token depending on your application needs.
131+
For example, if you are using Guard for authentication, you would use the `PostAuthenticationGuardToken`:
132+
133+
// tests/Controller/DefaultControllerTest.php
134+
namespace App\Tests\Controller;
135+
136+
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
137+
use Symfony\Component\BrowserKit\Cookie;
138+
use Symfony\Component\HttpFoundation\Response;
139+
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
140+
141+
class DefaultControllerTest extends WebTestCase
142+
{
143+
private $client = null;
144+
145+
private $user = null;
146+
147+
public function setUp()
148+
{
149+
$this->client = static::createClient();
150+
$this->user = $this->createUser()
151+
}
152+
153+
private function createUser() {
154+
155+
// create your user, save it and return it
156+
// ...
157+
158+
return $user;
159+
}
160+
161+
public function testSecuredHello()
162+
{
163+
$this->logInAsUser($user);
164+
$crawler = $this->client->request('GET', '/admin');
165+
166+
$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
167+
$this->assertSame('Admin Dashboard', $crawler->filter('h1')->text());
168+
}
169+
170+
171+
protected function logInAsUser(UserInterface $user)
172+
{
173+
$session = $this->client->getContainer()->get('session');
174+
175+
// the firewall context defaults to the firewall name
176+
$firewallContext = 'secured_area';
177+
$token = new PostAuthenticationGuardToken(
178+
$user,
179+
$firewallContext,
180+
array('ROLE_ADMIN')
181+
);
182+
$session->set('_security_'.$firewallContext, serialize($token));
183+
$session->save();
184+
185+
$cookie = new Cookie($session->getName(), $session->getId());
186+
$this->client->getCookieJar()->set($cookie);
187+
}
188+
189+

0 commit comments

Comments
 (0)