Skip to content

Instantly share code, notes, and snippets.

@vasilvestre
Last active June 18, 2020 15:05
Show Gist options
  • Save vasilvestre/ae8a95b0a4b9be598488cf8d18f3fc26 to your computer and use it in GitHub Desktop.
Save vasilvestre/ae8a95b0a4b9be598488cf8d18f3fc26 to your computer and use it in GitHub Desktop.
Programmatically login as User in Symfony 4.3+ to 5 App with Behat + Mink 1.8 + FriendsOfBehat/SymfonyExtension

The TestBrowserToken is a copy modified for my needs and taken from here

It's first a Symfony feature implemented in 5.1 here, it's just the mink adaptation with new super Symfony extension.

Feature:
In order to prove that login and acces to back office works
As a user
I want to login
Scenario:
Given I login as "ROLE_ADMIN" on firewall "main"
When I go to "/"
Then I should be on "/" #normally, we get redirected in my case to /login if not logged in
<?php
namespace App\Tests\Behat;
use Behat\Behat\Context\Context;
use Behat\Mink\Session;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\RouterInterface;
final class SecurityContext implements Context
{
/** @var Session */
private $session;
/** @var RouterInterface */
private $router;
/** @var KernelInterface */
private $kernel;
public function __construct(Session $session, RouterInterface $router, KernelInterface $kernel)
{
$this->session = $session;
$this->router = $router;
$this->kernel = $kernel;
}
/**
* @Given /^I login as "([^"]*)" on firewall "([^"]*)"$/
*/
public function iAmLoggedInAs(string $role, string $firewallContext = 'main'): void
{
$container = $this->kernel->getContainer();
/** @var UserRepository $userRepository */
$userRepository = $container->get(UserRepository::class);
/** @var User|null $user */
$user = $userRepository
->createQueryBuilder('u')
->where('u.roles like :role')
->setParameter('role', '%'.$role.'%')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if (!$user instanceof User) {
throw new \LogicException(sprintf('No user bo have been found having role %s', $role));
}
$token = new TestBrowserToken($user->getRoles(), $user);
$token->setAuthenticated(true);
$session = $container->get('session');
$session->set('_security_'.$firewallContext, serialize($token));
$session->save();
$this->session->setCookie($session->getName(), $session->getId());
return;
}
}
@francebenoit
Copy link

where is the code of your modify TestBrowserToken ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment