0

I implemented the lexik jwt bundle for symfony 2.8 in my application, and I am trying to use it with a user login or email, but I have not been able to do it in any way.

The bundle works correctly, but I have not been able to configure it to be able to authenticate by email or username and I have not found examples of how to do it through the documentation or internet.

my code is like the documentation show, i tried to implement it extending from JWTTokenValidator, but I have not been able to approach.

How can I configure it to achieve user authentication by email or username and password?

kmilo93sd
  • 791
  • 1
  • 15
  • 35

1 Answers1

1

I archivied auth by username and email,the only thing that must be done is to provide another user provider to the library. You only need a class that implements UserProviderInterface, specifically the loadUserByUsername method with your custom authentication logic. And then inject it as a dependency in the service of lexik jwt. for example:

 class AuthUserProvider implements UserProviderInterface
{

    /**
     * @var UserRepository
     */
    private $userManager;

    public function __construct(UserManager $userManager)
    {
        $this->userManager = $userManager;
    }

    public function loadUserByUsername($username)
    {
        $foundedUser = $this->userManager->findUserByUsernameOrEmail($username);

        if ($foundedUser === null) {
            throw new UsernameNotFoundException();
        }

        return $foundedUser;
    }

    public function refreshUser(UserInterface $user)
    {
        // TODO: Implement refreshUser() method.
    }

    public function supportsClass($class)
    {
        // TODO: Implement supportsClass() method.
    }
}

my bundle service.yml looks like this:

api_bundle.security.auth_user_provider:
        class: Project\TheOwn\ApiBundle\Security\AuthUserProvider
        arguments:
            - '@the_own.core.manager.user'
        public: true

and my security.yml :

security:
encoders:
    FOS\UserBundle\Model\UserInterface: sha512

providers:
    auth_user_provider:
        id: api_bundle.security.auth_user_provider
firewalls:
    login:
        pattern:  ^/api/signin
        stateless: true
        anonymous: true
        provider: auth_user_provider
        form_login:
            check_path:               /api/signin
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
            require_previous_session: false

    api:
        pattern: ^/api/
        security: true
        stateless: true
        provider: auth_user_provider
        guard:
            authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator

access_control:
    - { path: ^/api/signin, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
kmilo93sd
  • 791
  • 1
  • 15
  • 35