1

I have a User entity, which implements UserInterface, \Serializable, EquatableInterface

It is set in the security settings:

security:

    encoders:
        AppBundle\Entity\User:
            algorithm: sha512

    providers:
        our_db_provider:
            entity:
                class: AppBundle:User
                property: email

    firewalls:
        main:
            anonymous: ~
            provider: our_db_provider
            form_login:
                login_path: login
                check_path: login

    access_control:
        - { path: ^/ , roles: IS_AUTHENTICATED_ANONYMOUSLY}
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/registration, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        #...

I would like to select a user from the database and log in the current visitor, as the selected user.

$user = $em->getRepository('App\Entity\User')->find($user_id);

I have no idea, how to manage it. I am not using FOSUserBundle. I've searched for the solution, but I can't found anything, just the AuthenticationUtils, which only works with form submits.

Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • Possible duplicate of [How to programmatically login/authenticate a user?](http://stackoverflow.com/questions/9550079/how-to-programmatically-login-authenticate-a-user) – Pieter van den Ham Jan 05 '17 at 23:28
  • 1
    You might be asking how to switch to a user: http://symfony.com/doc/current/security/impersonating_user.html – Cerad Jan 06 '17 at 13:28

1 Answers1

1

In \Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener you can find lines that shows how to make authorization manually without performing a form submit:

$request->getSession()->set(Security::LAST_USERNAME, $username);

return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));

$this->providerKey can be taken from security.yml as a key from firewalls section.

If firewalls section looks like

    firewalls:
      secured_area:
        pattern:    ^/
        form_login:
          check_path: login_check
          login_path: login
        logout:
          path:   /logout

then providerKey = secured_area.

authenticationMananger can be taken from security.authentication.manager service.

Hope it will work!

Dmitry Grachikov
  • 316
  • 3
  • 11