Skip to content

doc(testing/http_authentication.rst) #9038

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
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
61 changes: 61 additions & 0 deletions testing/http_authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,64 @@ needs::
$this->client->getCookieJar()->set($cookie);
}
}

Note: Are you using Guard? You may adjust the token depending on your application needs.
For example, if you are using Guard for authentication, you would use the `PostAuthenticationGuardToken`:

// tests/Controller/DefaultControllerTest.php
namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;

class DefaultControllerTest extends WebTestCase
{
private $client = null;

private $user = null;

public function setUp()
{
$this->client = static::createClient();
$this->user = $this->createUser()
}

private function createUser() {

// create your user, save it and return it
// ...

return $user;
}

public function testSecuredHello()
{
$this->logInAsUser($user);
Copy link
Contributor

Choose a reason for hiding this comment

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

$this->user

$crawler = $this->client->request('GET', '/admin');

$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
$this->assertSame('Admin Dashboard', $crawler->filter('h1')->text());
}


protected function logInAsUser(UserInterface $user)
{
$session = $this->client->getContainer()->get('session');

// the firewall context defaults to the firewall name
$firewallContext = 'secured_area';
$token = new PostAuthenticationGuardToken(
$user,
$firewallContext,
array('ROLE_ADMIN')
);
$session->set('_security_'.$firewallContext, serialize($token));
$session->save();

$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}