x2df2na
x2df2na

Reputation: 55

symfony2 programmatically authenticate user

I just went through this tutorial: http://symfony.com/doc/current/cookbook/security/api_key_authentication.html (including "Storing Authentication in the Session")

It works and authorizes users by an api key and successfully stores authentication in the Session.

But, I've no any ideas how to programmatically authenticate user through that authentication method.

I've 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 seems like it used wrong authentication provider.

Can please someone tell me what I doing wrong? (:

Updated:

When authentication was done by method above, in session token is stored under "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: ~

Why instead of using "secured_area" firewall it uses "default"? How to properly force "secured_area" usage?

Upvotes: 4

Views: 4489

Answers (1)

Nawfal Serrar
Nawfal Serrar

Reputation: 2263

your user creation is not correct , you should use the user manager:

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

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

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

Then you can authenticate user with this :

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

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

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

Edit :

$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);

You can do it like this in a more conventional way, let me know if it helps getting the right firewall.

btw i am not sure if this is already in your symfony version yet, but there is an easier way :

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

Upvotes: 6

Related Questions