Symfony2 programmatically authenticates user

I just looked through this tutorial: http://symfony.com/doc/current/cookbook/security/api_key_authentication.html (including "Saving authentication in a session")

It works and authorizes users using the api key and successfully saves authentication in the session.

But I have no idea how to programmatically authenticate the user through this authentication method.

I tried something like:

$user = new User(
    'admin',
    null,
    ['ROLE_ADMIN']
);

$token = new PreAuthenticatedToken($user, null, "secured_area", $user->getRoles());
$this->get("security.token_storage")->setToken($token);

$request = $this->get("request");
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);

but it looks like he used the wrong authentication provider.

Can someone tell me what I am doing wrong? (

Updated:

When authentication was performed using the method described above, the session token is stored in the default firewall.

security:
    providers:
        api_key_user_provider:
            id: api_key_user_provider

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt|error)|css|images|js)/
            security: false

        secured_area:
            pattern: ^/admin
            simple_preauth:
                authenticator: apikey_authenticator

        default:
            anonymous: ~

"secure_area" "default"? "secure_area"?

+4
1

, :

$userManager = $this->container->get('fos_user.user_manager');

// Create our user and set details
$user = $userManager->createUser();
$user->setUsername('username');
$user->setEmail('email@domain.com');
$user->setPlainPassword('password');
//$user->setPassword('encrypted_password');
$user->setEnabled(true);
$user->setRoles(array('ROLE_ADMIN'));

// Update the user
$userManager->updateUser($user, true);

:

$token = new UsernamePasswordToken(
    $user,
    $user->getPassword(),
    'secured_area',
    $user->getRoles()
);

$this->get('security.context')->setToken($token);

$request->getSession()->set('_security_secured_area', serialize($token));

:

$token = new UsernamePasswordToken($user, $user->getPassword(), "secured_area", $user->getRoles());
$this->get("security.context")->setToken($token);

$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);

, , , , .

btw , symfony, :

https://github.com/symfony/symfony/pull/13062

+6

All Articles