Question

Using the FOSUserbundle, I want to achieve the following:

1) User submits a POST with "username" and "password" parameters. Password is in plaintext.

2) In a controller, I parse the parameters as usual:

/**
 * @Route("/api/token",name="api_token")
 */
public function tokenAction(Request $request) {

    $username = $request->get('username');
    $password = $request->get('password');

    // ...
}

3) Finally, if the credentials match, I return something.

Note that I want to do this WITHOUT modifying the session, i.e. without actually authenticating the user and setting a token. I only want to check if the credentials match.

UPDATE

The accepted answer works, but only under the assumption that you have an active session. If you want to solve the case where you simply expose a REST layer or the like (which was my usecase), you can do the following, assuming your usernames are unique:

/**
 * @Route("/api/token",name="api_token", options={"expose"=true})
 */
public function getTokenAction(Request $request) {
    $username = $request->get('username');
    $password = $request->get('password');

    $user = $this->getDoctrine()
                 ->getRepository('YourUserClass')
                 ->findOneBy(["username" => $username]);

    $encoder = $this->get('security.encoder_factory')->getEncoder($user);

    $isValidPassword = $encoder->isPasswordValid($user->getPassword(),
                                                 $password,
                                                 $user->getSalt());

    if ($isValidPassword) {
        // Handle success
    } else {
        // Handle error
    }
}
Was it helpful?

Solution

You should use an authentication service to do this, writing all code in controller is not a best practice. Anyway, to your answer, you can use this:

/**
 * @Route("/api/token",name="api_token")
 */
public function tokenAction(Request $request) {

    $username = $request->get('username');
    $password = $request->get('password');

    // fetch your user using user name
    $user = ...

   //If your controller is extended from Symfony\Bundle\FrameworkBundle\Controller\Controller
   $encoder = $this->get('security.encoder_factory')->getEncoder($user);
   //If you are extending from other ContainerAware Controller you may have to do 
   //$this->container->get('security.encoder_factory')->getEncoder($user)

   //Check your user
    $isValidPassword = $encoder->isPasswordValid(
            $user->getPassword(),
            $password,
            $user->getSalt()
    );

    if ($isValidPassword) {
       //.... do your valid stuff
    }else{
       //... Do your in valid stuff
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top