How to Programmatically Login/Authenticate a User

How to programmatically login/authenticate a user?

Yes, you can do this via something similar to the following:

use Symfony\Component\EventDispatcher\EventDispatcher,
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken,
Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

public function registerAction()
{
// ...
if ($this->get("request")->getMethod() == "POST")
{
// ... Do any password setting here etc

$em->persist($user);
$em->flush();

// Here, "public" is the name of the firewall in your security.yml
$token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles());

// For older versions of Symfony, use security.context here
$this->get("security.token_storage")->setToken($token);

// Fire the login event
// Logging the user in above the way we do it doesn't do this automatically
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);

// maybe redirect out here
}
}

The event firing at the end isn't automatically done when you set a token into the context, whereas it would be normally when using eg a login form or similar. Hence the reason for including it here. You may need to adjust the type of token used, depending on your use case - the UsernamePasswordToken shown above is a core token, but you can use others if required.

Edit: Adjusted the above code to explain the 'public' parameter and also add in the roles of the user into the token creation, based on Franco's comment below.

symfony2 programmatically authenticate user

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@domain.com');
$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

Programmatically login User on Symfony2


// Create my new custom token (loading the roles of the user)
$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($this->getUser()->getUsername(), null, "secured_area", array($dynamic_rolename));

In the above section you are using UsernamePasswordToken for the token creation.This accepts 4 parameters. The first parameter can be :

The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method.

You are just passing the username . Pass the user entity instead so that you can have $this->getUser()->getId() working.

Programmatically login to site using Google OAuth2

What I was asking is not possible in the time of writing the question.
What we did to solve the issue is to extend the life of the token for the account that is used to login to SiteA and set it it in the header of the request from SiteB:

connection.setRequestProperty("Authorization", token);

We changed the lifespan of the token from the database and since this are internal systems the long life of the token is not a problem.

Another option is to follow How to get offline token and refresh token and auto-refresh access to Google API and generate an offline token, but the idea is still the same.

Hope this helps someone.

Laravel can not login user programmatically


try use like that

Login and "remember" the given user...

Auth::login($user, true);

otherwise specify guard like that

Auth::guard('admin')->login($user);

third way login using id

Auth::loginUsingId(1);

Login and "remember" the given user...

Auth::loginUsingId(1, true);


Related Topics



Leave a reply



Submit