<?php
namespace App\Controller;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class SecurityCognitoController extends AbstractController
{
/**
* Link to this controller to start the "connect" process
*/
#[Route("/login-aws", name:"connect_cognito_start")]
public function connectAction(ClientRegistry $clientRegistry)
{
// will redirect to AWS Cognito!
return $clientRegistry
->getClient('cognito') // key used in config/packages/knpu_oauth2_client.yaml
->redirect();
}
/**
* After going to Cognito, you're redirected back here
* because this is the "callback URL" you configured
* in AWS Cognito APP settings
*/
#[Route("/security/cognito/check", name:"connect_cognito_check")]
public function connectCheckAction(Request $request, ClientRegistry $clientRegistry)
{
// ** if you want to *authenticate* the user, then
// leave this method blank and create a Guard authenticator
// $client = $clientRegistry->getClient('cognito');
// dd('dd',$client);
// try {
// // the exact class depends on which provider you're using
// $user = $client->fetchUser();
// // do something with all this new power!
// // e.g. $name = $user->getFirstName();
// var_dump($user); die;
// // ...
// } catch (IdentityProviderException $e) {
// // something went wrong!
// // probably you should return the reason to the user
// var_dump($e->getMessage()); die;
// }
}
#[Route("/logout-aws", name: "app_logout")]
public function logout(Request $request, ClientRegistry $clientRegistry, RequestStack $requestStack, Security $security)
{
$session = $requestStack->getSession();
$access_token = $session->get('token');
$values = $this->getParameter('cognito');
$client = $clientRegistry->getClient('cognito');
$provider = $client->getOAuth2Provider();
$state = $session->get('knpu.oauth2_client_state');
$client_id = ($values['client_id']) ? $values['client_id'] : '';
$region = ($values['region']) ? $values['region'] : '';
$cognitoDomain = ($values['cognito_domain']) ? $values['cognito_domain'] : '';
$domain = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();;
$security->getToken()->setAuthenticated(false);
$targetUrl = 'https://' . $cognitoDomain . '.auth.' . $region . '.amazoncognito.com/logout?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode($domain) . '/security/cognito/check&state=' . $state .'&scope=openid+profile+email';
return new RedirectResponse($targetUrl);
}
}