Skip to content

Simpler testing of security protected resources #26839

@javiereguiluz

Description

@javiereguiluz
Q A
Bug report? no
Feature request? yes
BC Break report? no
RFC? yes
Symfony version 4.2

The official Symfony solution to log in a user in the app before testing security-protected resources looks like this:

public function testSomething()
{
    $client = static::createClient();

    // --- log in the user ----------------------------------------------------
    $username = 'admin';
    $session = $client->getContainer()->get('session');

    // the firewall context defaults to the firewall name
    $firewallContext = 'secured_area';

    $token = new UsernamePasswordToken($username, null, $firewallContext, array('ROLE_ADMIN'));
    $session->set('_security_'.$firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $client->getCookieJar()->set($cookie);
    // --- end of user log in -------------------------------------------------

    // ... test something ...
}

I think we can do better. I'd like to have a different way to test security-protected resources. A solution that is simple to use and easy to understand. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    DXDX = Developer eXperience (anything that improves the experience of using Symfony)Security

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions