Search code examples
symfonyauthenticationfosuserbundle

How to authorize custom user from db in Symfony4


I just need to authorize custom user. Without any froms, tokens and etc. I have user entity in my DB. User class is already configuren it fos_user.yaml:

fos_user:
db_driver: orm
firewall_name: main
from_email:
    address: '***@*******.**'
    sender_name: '**.****.**'
user_class: App\Entity\User

Is it possible? Somethong like

Authurizer::authorize($userEntity)

Thanks.


Solution

  • Authorization in Symfony done Tokens. To be logged in Symfony's World you'll need to set a Token.

    One of the common use cases is "auto login" right after registration.

    Take a look at this article -> https://ourcodeworld.com/articles/read/459/how-to-authenticate-login-manually-an-user-in-a-controller-with-or-without-fosuserbundle-on-symfony-3

    especially for that part

    $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
    $this->get('security.token_storage')->setToken($token);
    

    BUT also take a look at symfony's impersonalizaiton => https://symfony.com/doc/current/security/impersonating_user.html

    It basically allows you to switch users without filling out forms and knowing users' credentials