Twig is_granted not working in Behat script

I have this Behat setting:

default: extensions: Behat\Symfony2Extension: ~ Behat\MinkExtension: sessions: default: symfony2: ~ 

And this scenario:

 Scenario: Event list for authenticated user Given I am authenticated Then I should see pagination control And I should be able to change list page 

I check to see if the user has been authenticated, and if so, show him Twig page control:

 {% if is_granted('IS_AUTHENTICATED_FULLY') %} ... 

Related Behat Context:

 /** * @Given I am authenticated */ public function iAmAuthenticated() { $user = new User('test', null, ['ROLE_USER']); $token = new UsernamePasswordToken($user, null, 'test', $user->getRoles()); $this->getTokenStorage()->setToken($token); } /** * @Then I should see pagination control */ public function iShouldSeePaginationControl() { $this->assertSession()->elementExists('css', 'ul.pagination'); } 

I get true for

 $this->kernel ->geContainer() ->get('security.authorization_checker') ->isGranted('IS_AUTHENTICATED_FULLY') 

in my iShouldSeePaginationControl() , but it is false in the rendered content.

What am I missing?

+5
source share
2 answers

I assume that you are using a different instance of the container at your runtime and in your template.

AFAIR, the symfony2 driver uses BrowserKit under the hood to navigate your site. The container that will be used on your web page will then be initiated by the PHP Engine of your web server (and not Behat). If so, it is absolutely impossible to make changes to the container at runtime in step and expect the web server to know about them.

A simple solution is to actually enter the execution step (via the web interface), instead of manually setting the marker.

Another difficult way, if you absolutely want to enter the system programmatically, is to serialize the created token on the HDD and register some kind of logic (for example, the kernel.request listener), which will check if this file is available and enter the unesterified token into security context. If you do, MAKE SURE you only enable this logic in the TEST environment, as this could potentially be a security breach.

0
source

The problem is that you have 2 instances of Symfony running:

  • One core for Behat that has been initialized.
  • Secondly, initialized apache / nginx, which was initiated by connecting Mink to the server.

Decision

For this, we had a solution in another project (with Zend). We created a service that created an additional configuration for authorization:

  • If the file exists and the project was in DEV mode, it was loaded at the initialization stage.

Then in hook / step we can call the service that generates such a file, and after the script, delete it. Thus, you can have any registered user in your project.

Another way is to call steps that will record you into your project through a standard form.

0
source

Source: https://habr.com/ru/post/1273164/


All Articles