src/Controller/GoogleController.php line 18

  1. <?php
  2. namespace App\Controller;
  3. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  4. use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. class GoogleController extends AbstractController
  9. {
  10.     /**
  11.      * Link to this controller to start the "connect" process
  12.      *
  13.      * @Route("/connect/google", name="connect_google_start")
  14.      */
  15.     public function connectAction(ClientRegistry $clientRegistry)
  16.     {
  17.         // on Symfony 3.3 or lower, $clientRegistry = $this->get('knpu.oauth2.registry');
  18.         // will redirect to Google!
  19.         return $clientRegistry
  20.             ->getClient('google'// key used in config/packages/knpu_oauth2_client.yaml
  21.             ->redirect([
  22.                 'email''profile' // the scopes you want to access
  23.             ], []);
  24.     }
  25.     /**
  26.      * After going to Google, you're redirected back here
  27.      * because this is the "redirect_route" you configured
  28.      * in config/packages/knpu_oauth2_client.yaml
  29.      *
  30.      * @Route("/connect/google/check", name="connect_google_check")
  31.      */
  32.     public function connectCheckAction(Request $requestClientRegistry $clientRegistry)
  33.     {
  34.         // ** if you want to *authenticate* the user, then
  35.         // leave this method blank and create a Guard authenticator
  36.         // (read below)
  37.         /** @var \KnpU\OAuth2ClientBundle\Client\Provider\GoogleClient $client */
  38.         $client $clientRegistry->getClient('google');
  39.         try {
  40.             // the exact class depends on which provider you're using
  41.             /** @var \League\OAuth2\Client\Provider\GoogleUser $user */
  42.             $user $client->fetchUser();
  43.             // do something with all this new power!
  44.             $name $user->getFirstName();
  45.             var_dump($user); die;
  46.             // ...
  47.         } catch (IdentityProviderException $e) {
  48.             // something went wrong!
  49.             // probably you should return the reason to the user
  50.             var_dump($e->getMessage()); die;
  51.         }
  52.     }
  53. }