public function authenticate(TokenInterface $token)
 {
     try {
         $user = $this->userProvider->loadUserByAccessToken($token->getAccessToken());
         $authenticatedToken = new OAuth2Token($user->getRoles());
         $authenticatedToken->setAccessToken($token->getAccessToken());
         $authenticatedToken->setRefreshToken($token->getRefreshToken());
         $authenticatedToken->setUser($user);
         return $authenticatedToken;
     } catch (\Exception $e) {
         throw new AuthenticationException('The OAuth2 Access Token is invalid.');
     }
     throw new AuthenticationException('OAuth2 authentication failed.');
 }
 /**
  * {@inheritDoc}
  */
 protected function attemptAuthentication(Request $request)
 {
     // Look for an authorization code
     if ($request->query->has('code')) {
         $session = $request->getSession();
         // Do with have an authorization code instead?
         // and do the states match?
         if ($session->get('state') == $request->query->get('state')) {
             // Swap authorization code for access token
             $tokenData = [];
             $client = new Client(['timeout' => 2, 'connect_timeout' => 2]);
             if ($this->validateSSL === false) {
                 $client = new Client(['ssl.certificate_authority' => FALSE]);
             }
             $request = new \GuzzleHttp\Psr7\Request('POST', $this->serverTokenUri, ['Content-Type' => 'application/x-www-form-urlencoded'], http_build_query(['grant_type' => 'authorization_code', 'code' => $request->query->get('code'), 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'redirect_uri' => $this->redirectUri]));
             try {
                 $response = $client->send($request);
                 $tokenData = json_decode($response->getBody()->getContents(), true);
             } catch (\Exception $e) {
                 throw new AuthenticationException('Authorization Code Invalid');
             }
             if (isset($tokenData) && is_array($tokenData)) {
                 $token = new OAuth2Token();
                 $token->setAccessToken($tokenData['access_token']);
                 if (isset($tokenData['refresh_token'])) {
                     $token->setRefreshToken($tokenData['refresh_token']);
                 }
                 $authToken = $this->authenticationManager->authenticate($token);
                 if (isset($authToken)) {
                     return $authToken;
                 }
             }
         }
     }
     return null;
 }