使用AOUTH2和Guard授权symfony4用户

时间:2019-03-27 10:15:27

标签: php symfony4

我在symfony上使用guard和oauth2来保护API有点困惑。我有一个控制器来处理来自FB或其他提供程序的回调,然后根据我在网上找到的示例制作了此身份验证器:

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);
}

// ...
}

此类的核心是getUser()方法。这很好,我可以从FB获取信息并将其保存到我的本地数据库中。但是,我该怎么做才能真正验证用户身份?

0 个答案:

没有答案