Symfony 3 FB Login - After OAuth Login flow I go back at Login page because the authentication expires instantly
<p>I am trying to implement Facebook Connect in a web-site. However when I go through the connect process I am returned to Login page page because the authentication expires instantly.
I also have a separate regular registration and login present</p>

<p>Controller:</p>

<pre><code>&lt;?php

namespace Vendor\GiftBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class FacebookConnectController extends Controller
{
    /**
     * @Route("/connect/facebook", name="connect_facebook")
     */
    public function connectFacebookAction(Request $request)
    {

        // redirect to Facebook
        $facebookOAuthProvider = $this-&gt;get('app.facebook_provider');
        $url = $facebookOAuthProvider-&gt;getAuthorizationUrl([
            // these are actually the default scopes
            'scope' =&gt; ['public_profile', 'email'],
            //'redirect_uri' =&gt; [$redir],
        ]);

        return $this-&gt;redirect($url);
    }

    /**
     * @Route("/connect/facebook-check", name="connect_facebook_check")
     */
    public function connectFacebookActionCheck()
    {
        // will not be reached!
    }
}
</code></pre>

<p>Facebook Authenticator:</p>

<pre><code>&lt;?php

namespace Vendor\GiftBundle\Security;

use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Vendor\GiftBundle\Entity\Logins;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class FacebookAuthenticator extends AbstractGuardAuthenticator
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this-&gt;container = $container;
    }

    public function getCredentials(Request $request)
    {
        if ($request-&gt;getPathInfo() != '/connect/facebook-check') {
            // skip authentication unless we're on this URL!
            return null;
        }
        if ($code = $request-&gt;query-&gt;get('code')) {
            return $code;
        }
        // no code! Something went wrong. Quite probably the user denied our app access
        // you could read the error, error_code, error_description, error_reason query params
        // http://localhost:8000/connect/facebook-check?error=access_denied&amp;error_code=200&amp;error_description=Permissions+error&amp;error_reason=user_denied&amp;state=S2fKgHJSZSJM0Qs2fhKL6USZP50KSBHc#_=_

        throw CustomAuthenticationException::createWithSafeMessage(
            'There was an error getting access from Facebook. Please try again.'
        );
    }

    public function getUser($authorizationCode, UserProviderInterface $userProvider)
    {
        //$user = new Logins();
        $facebookProvider = $this-&gt;container-&gt;get('app.facebook_provider');
        try {
            // the credentials are really the access token
            $accessToken = $facebookProvider-&gt;getAccessToken(
                'authorization_code',
                ['code' =&gt; $authorizationCode]
            );
        } catch (IdentityProviderException $e) {
            // probably the authorization code has been used already
            $response = $e-&gt;getResponseBody();
            $errorCode = $response['error']['code'];
            $message = $response['error']['message'];
            throw CustomAuthenticationException::createWithSafeMessage(
                'There was an error logging you into Facebook - code '.$errorCode
            );

        }

        /** @var FacebookUser $facebookUser */
        $facebookUser = $facebookProvider-&gt;getResourceOwner($accessToken);
        $email = $facebookUser-&gt;getEmail();

        //$em = $this-&gt;getDoctrine()-&gt;getManager();
        //$check = $em-&gt;getRepository('VendorGiftBundle:Logins')-&gt;findByEmail($email);

        $em = $this-&gt;container-&gt;get('doctrine')-&gt;getManager();
        // 1) have they logged in with Facebook before? Easy!
        $existingUser = $em-&gt;getRepository('VendorGiftBundle:Logins')
            -&gt;findOneBy(array('fbid' =&gt; $facebookUser-&gt;getId()));
        if ($existingUser) {
            return $existingUser;
        }
        // 2) do we have a matching user by email?
        $user = $em-&gt;getRepository('VendorGiftBundle:Logins')
                    -&gt;findOneBy(array('email' =&gt; $email));
        // 3) no user? Perhaps you just want to create one
        //      or maybe you want to redirect to a registration (in that case, keep reading_
        if (!$user) {
            $user = new Logins();
            $user-&gt;setEmail($email);
            $user-&gt;setFirstname($facebookUser-&gt;getFirstName());
            $user-&gt;setLastname($facebookUser-&gt;getLastName());
            $user-&gt;setCity($facebookUser-&gt;getLocale());
            $user-&gt;setCreationtime();
            $user-&gt;setStatus(1);
            // set an un-encoded password, which basically makes it *not* possible
            // to login with any password
            $user-&gt;setPassword('no password');
        }
        // make sure the Facebook user is set
        $user-&gt;setFbid($facebookUser-&gt;getId());
        $em-&gt;persist($user);
        $em-&gt;flush();
        return $user;
        /*
        if(!$check){
            $hash = uniqid();
            //Encode the password (you could also do this via Doctrine listener)
            $password = $this-&gt;get('security.password_encoder')
                -&gt;encodePassword($user, $hash);
            $user-&gt;setEmail($email);
            $user-&gt;setFirstname($facebookUser-&gt;getFirstName());
            $user-&gt;setLastname($facebookUser-&gt;getLastName());
            $user-&gt;setCity($facebookUser-&gt;getLocale());
            $user-&gt;setPassword($password);
            $user-&gt;setCreationtime();
            $user-&gt;setStatus(1);
            // 4) save the User!
            $em = $this-&gt;getDoctrine()-&gt;getManager();
            $em-&gt;persist($user);
            $em-&gt;flush();
            return $user;
        }
        return $user;
         * 
         */
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return true;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        // this would happen if something went wrong in the OAuth flow
        $request-&gt;getSession()-&gt;set(Security::AUTHENTICATION_ERROR, $exception);
        $url = $this-&gt;container-&gt;get('router')
            -&gt;generate('login_route');
        return new RedirectResponse($url);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        $key = '_security.main.target_path'; #where "main" is your firewall name

        //check if the referrer session key has been set 
        if ($this-&gt;container-&gt;get('session')-&gt;has($key)) {
            //set the url based on the link they were trying to access before being authenticated
            $url = $this-&gt;container-&gt;get('session')-&gt;get($key);

            //remove the session key
            $this-&gt;container-&gt;get('session')-&gt;remove($key);
        }
        //if the referrer key was never set, redirect to a default route
        else{
            $url = $this-&gt;container-&gt;get('router')-&gt;generate('home_page');

        }

        return new RedirectResponse($url); 
        // todo - remove needing this crazy thing
        /*
        $targetPath = $request-&gt;getSession()-&gt;get('_security.'.$providerKey.'.target_path');

        if ($targetPath) { 
            $router = $this-&gt;container-&gt;get('router');
            $targetPath = $router-&gt;generate('home_page');
        }
        return new RedirectResponse($targetPath);
         * 
         */
    }

    public function supportsRememberMe()
    {
        return true;
    }



    /**
     * Called when an anonymous user tries to access an protected page.
     *
     * In our app, this is never actually called, because there is only *one*
     * "entry_point" per firewall and in security.yml, we're using
     * app.form_login_authenticator as the entry point (so it's start() method
     * is the one that's called).
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        // not called in our app, but if it were, redirecting to the
        // login page makes sense
        $url = $this-&gt;container-&gt;get('router')
            -&gt;generate('home_page');
        return new RedirectResponse($url);

    }

    protected function getDefaultSuccessRedirectUrl()
    {
        return $this-&gt;container-&gt;get('router')-&gt;generate('home_page');
    }

    protected function getLoginUrl()
    {
        return $this-&gt;container-&gt;get('router')-&gt;generate('login_route');
    }

    public function getDoctrine()
    {
        return $this-&gt;container-&gt;get('doctrine');
    }

    public function get($id)
    {
        return $this-&gt;container-&gt;get($id);
    }

}
</code></pre>

<p>Security.yml:</p>

<pre><code>security:

    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers

    encoders:
        Vendor\GiftBundle\Entity\Logins:
            algorithm: bcrypt
            cost: 13
        Symfony\Component\Security\Core\User\User:
            algorithm: bcrypt
            cost: 13

    #make admin inherit user access
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
#        ROLE_SUPER_ADMIN: ROLE_ADMIN

    #provider of user authetification name, in our case, email
    providers:
        doctrine1:
            entity: 
                class: Vendor\GiftBundle\Entity\Logins
                property: email
#        in_memory:
#            memory: ~


    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            #pattern: ^/.*
            #security: false
            anonymous: ~
            form_login:
                login_path: /login
                check_path: /login_check
                csrf_token_generator: security.csrf.token_manager
                username_parameter: _email
            provider: doctrine1

            logout:
                path: /logout
                target: /

            anonymous: ~
            guard:
                authenticators:
                    - app.facebook_authenticator
                #entry_point: app.form_login_authenticator
            #anonymous:    ~
            # activate different ways to authenticate

            # http_basic: ~
            # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # http://symfony.com/doc/current/cookbook/security/form_login_setup.html

    access_control:
        - { path: ^/connect, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/reset, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/sec, role: ROLE_USER }
        - { path: ^/admin, role: ROLE_ADMIN }
</code></pre>