SupaCoco
SupaCoco

Reputation: 1665

Symfony2 authenticating users through a webservice

I'm currently dealing with Symfony2's Security component.

I try to authenticate users against a webservice. To authenticate a user, I have to provide to the webservice a username and a password.

I know that I've got to create a class that implements UserProvider. But the loadUserByUsername function doesn't fit my webservice needs : in order to authenticate a user, it ask for both username and password whereas the UserProvider's function only requires username.

Here is a similar question to the problem I face : Symfony2 authentication without UserProvider

I've been struggling on this problem for a couple of days...

Upvotes: 5

Views: 2458

Answers (2)

Mauro
Mauro

Reputation: 1487

I fixed this problem in that way:

services.yml:

services:
     user_provider:
         class: "%my_class%"
         arguments: ["@service_container"]

WebServiceUserProvider.php

/**
 * @param ContainerInterface $container
 */
public function __construct(ContainerInterface $container)
{
    $this->apiClient = $container->get('api_client');
    $this->request = $container->get('request');
}

and use $password = $this->request->get('password'); in your loadUserByUsername method

Upvotes: 2

Praveesh
Praveesh

Reputation: 1327

One way of accomplishing this would be to load the user by the username and then validate the password. If the a user exists for the given username and the password entered matches with the password of that user, then authenticate the user. Example:

public function userLogin($username, $password)
{
    $em = $this->getEntityManager();
    $query = $em->createQuery('SELECT u FROM VenomCoreBundle:User u WHERE u.username = :username OR u.email = :username AND u.isDeleted <> 1 ')
            ->setParameter('username', $username);
    try {
        $entity = $query->getSingleResult();
        if (count($entity) > 0) {
            $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
            $passwordEnc = $encoder->encodePassword($password, $entity->getSalt());
            $userPassword = $entity->getPassword();

            if ($passwordEnc == $userPassword) {
                $tokenValue = $entity->getUserToken();
                $profile = $entity->getUserProfile();
                if(!$profile) {
                    return false;
                }
                $userName = $profile->getFullName();



                $response = array(
                    'token' => $tokenValue,
                    'username' => $userName
                );
            } else {
                return false;
            }
        }
    } catch (\Doctrine\Orm\NoResultException $e) {
        return false;
    }

    return $response;
}

Upvotes: 0

Related Questions