dongzhuo7291 2019-03-27 10:15 采纳率: 100%
浏览 34

使用OAUTH2和Guard在symfony 4上授权用户

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看