Symfony2 authenticates users through a web service

I am currently working with the Symfony2 Security component.

I am trying to authenticate users using webservice. To authenticate a user, I must provide the web service with a username and password.

I know that I need to create a class that implements UserProvider. But the loadUserByUsername function does not meet my web service needs: for user authentication, it asks for a username and password, while for the UserProvider function only a username is required.

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

I tried this problem for several days ...

+5
source share
2 answers

I fixed this problem as follows:

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 the loadUserByUsername method

+2
source

One way to achieve this is to load the user by username and then confirm the password. If a user exists for a given username and the entered password matches the password for that user, 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;
}
0
source

All Articles