/**
  * @param TokenInterface $token
  *
  * @return OAuthToken|TokenInterface
  * @throws \Symfony\Component\Security\Core\Exception\AuthenticationException
  */
 public function authenticate(TokenInterface $token)
 {
     try {
         $tokenString = $token->getToken();
         $user = $this->userProvider->loadUserByToken($tokenString);
         $token = new OAuthToken($user->getRoles());
         $token->setToken($tokenString);
         $token->setUser($user);
         $token->setAuthenticated(true);
         return $token;
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->alert('Can not authenticate user', array('message' => $e->getMessage()));
         }
     }
     throw new AuthenticationException('The OAuth authentication failed.');
 }
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $accessToken = $this->getBearerTokenFromHeader($request);
     if (false === $accessToken) {
         $accessToken = $this->getBearerTokenFromQuery($request);
     }
     if (false === $accessToken) {
         if ($this->logger) {
             $this->logger->alert(sprintf('Token type %s was not found neither header nor query', $this->tokenType));
         }
         $this->createForbiddenResponse($event);
     }
     $token = new OAuthToken();
     $token->setToken($accessToken);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         // ... you might log something here
         // To deny the authentication clear the token. This will redirect to the login page.
         // Make sure to only clear your token, not those of other authentication listeners.
         // $token = $this->securityContext->getToken();
         // if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
         //     $this->securityContext->setToken(null);
         // }
         // return;
         // Deny authentication with a '403 Forbidden' HTTP response
         if ($this->logger) {
             $this->logger->alert('Authentication exception', array('message' => $failed->getMessage()));
         }
         $this->createForbiddenResponse($event);
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->alert('Authentication exception', array('message' => $e->getMessage()));
         }
         $this->createForbiddenResponse($event);
     }
     // By default deny authorization
     $this->createForbiddenResponse($event);
 }