I am a bit confusing using guard and oauth2 on symfony to secure an API. I have a controller to handle the callback from FB or another provider, then I made this authenticator from an example I find online:
class FacebookAuthenticator extends SocialAuthenticator
{
private $clientRegistry;
private $em;
public function __construct(ClientRegistry $clientRegistry, EntityManagerInterface $em)
{
$this->clientRegistry = $clientRegistry;
$this->em = $em;
}
public function supports(Request $request)
{
return $request->attributes->get('_route') === 'connect_facebook_check';
}
public function getCredentials(Request $request)
{
return $this->fetchAccessToken($this->getFacebookClient());
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
/** @var FacebookUser $facebookUser */
$facebookUser = $this->getFacebookClient()
->fetchUserFromToken($credentials);
$email = $facebookUser->getEmail();
$user = $this->em->getRepository(User::class)
->findOneBy(['email' => $email]);
if(!$user) {
$user = new User();
$user->setCreated(new \DateTime());
$user->setEmail($facebookUser->getEmail());
}
$user->setLastLogin(new \DateTime());
$this->em->persist($user);
$this->em->flush();
return $user;
}
/**
* @return FacebookClient
*/
private function getFacebookClient()
{
return $this->clientRegistry->getClient('facebook');
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
];
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
/**
* Called when authentication is needed, but it's not sent.
* This redirects to the 'login'.
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$data = [
'message' => 'Authentication Required'
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
// ...
}
the core of this class is the getUser() method. This works just fine, I can get info from FB and save it to my local db. However, what should I do to actually authenticate the user?