Last active
May 9, 2019 10:34
-
-
Save bichotll/cc043b14e97d67dda677 to your computer and use it in GitHub Desktop.
symfony2 - forced and secure user authentication (login) and logout (fos rest example)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//reference http://hasin.me/2013/10/27/how-to-login-a-user-programatically-in-symfony2/ | |
//... | |
class UserController extends FOSRestController implements ClassResourceInterface { | |
//... | |
/** | |
* Authenticate a user with Symfony Security | |
* | |
* @Rest\RequestParam(name="username", nullable=true) | |
* @Rest\RequestParam(name="password", nullable=true) | |
* | |
* @param ParamFetcherInterface $paramFetcher | |
* @Rest\Post("/authentication") | |
* @Rest\View() | |
*/ | |
public function authenticationAction(ParamFetcherInterface $paramFetcher) { | |
$username = $paramFetcher->get('username'); | |
$pwd = $paramFetcher->get('password'); | |
$em = $this->getDoctrine(); | |
$repo = $em->getRepository("ApplicationSonataUserBundle:User"); | |
$user = $repo->findOneBy(array( | |
'username' => $username | |
)); | |
//encode pwd | |
$encoderService = $this->get('security.encoder_factory'); | |
$encoder = $encoderService->getEncoder($user); | |
$encodedPwd = $encoder->encodePassword($pwd, $user->getSalt()); | |
//print_r($user->getPlainPassword()); die; | |
if (!$user || $encodedPwd !== $user->getPassword()) { | |
$data = array( | |
'error' => 'User not found' | |
); | |
$view = $this->view($data, 401); | |
} else { | |
$token = new UsernamePasswordToken($user, null, "main", $user->getRoles()); | |
$this->get("security.context")->setToken($token); //now the user is logged in | |
//now dispatch the login event | |
$request = $this->get("request"); | |
$event = new InteractiveLoginEvent($request, $token); | |
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event); | |
$data = array('authentication' => true); | |
$view = $this->view($data, 201); | |
} | |
return $this->handleView($view); | |
} | |
//... | |
/** | |
* Logout user | |
* | |
* @Rest\Post("/logout") | |
* @Rest\View() | |
*/ | |
public function logoutAction() { | |
try { | |
$this->get("request")->getSession()->invalidate(); | |
$this->get("security.context")->setToken(null); | |
return true; | |
} catch (\Exception $e) { | |
return false; | |
} | |
} | |
//... | |
} | |
//... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment