繁体   English   中英

获取 OAuth 凭据时出错:“OAuthException:已使用此授权代码。”

[英]Error fetching OAuth credentials: "OAuthException: This authorization code has been used."

我找到了很多关于这个问题的教程。 但是他们都没有解决我的问题。 所以,我正在尝试在 Symfony 4 上遵循 OAuth2 Facebook 的本教程

当我点击我的按钮“Connexion with Facebook”时,我有一个包含消息的空白页面:

获取 OAuth 凭据时出错:“OAuthException:已使用此授权码。”。

我在一些教程上看到关于 accessToken、longliveAccessToken 等的问题。

但是我不知道在我的代码中做什么来解决这个问题。

这是我的 FacebookAuthenticator.php 代码:

    <?php

namespace App\Security;

use App\Entity\User; // your user entity
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
use KnpU\OAuth2ClientBundle\Client\Provider\FacebookClient;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

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)
    {
        // continue ONLY if the current ROUTE matches the check ROUTE
        return $request->attributes->get('_route') === 'connect_facebook_check';
    }

    public function getCredentials(Request $request)
    {
        // this method is only called if supports() returns true

        // For Symfony lower than 3.4 the supports method need to be called manually here:
        // if (!$this->supports($request)) {
        //     return null;
        // }

        return $this->fetchAccessToken($this->getFacebookClient());
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        /** @var FacebookUser $facebookUser */
        $facebookUser = $this->getFacebookClient()
            ->fetchUserFromToken($credentials);


        // 1) have they logged in with Facebook before? Easy!
        $existingUser = $this->em->getRepository(User::class)
            ->findOneBy(['facebookId' => $facebookUser->getId()]);
        if ($existingUser) {
            return $existingUser;
        }

        // 2) do we have a matching user by email?
        $user = $this->em->getRepository(User::class)
            ->findOneBy(['email' => $email]);

        // 3) Maybe you just want to "register" them by creating
        // a User object
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";

        if(!$user){
        $user = new User();
        }
        $user->setFacebookId($facebookUser->getId());
        $user->setUsername($facebookUser->getEmail());
        $user->setPassword(password_hash(substr( str_shuffle( $chars ), 0, 10), PASSWORD_DEFAULT));
        $user->setPrenom($facebookUser->getFirstName());
        $user->setNom($facebookUser->getLastName());
        $user->setEmail($facebookUser->getEmail());
        $user->setEnabled(true);
        $user->setSocialAuthentication(true);
        $this->em->persist($user);
        $this->em->flush();


        return $user;

    }

    /**
     * @return FacebookClient
     */
    private function getFacebookClient()
    {

        return $this->clientRegistry
            // "facebook_main" is the key used in config/packages/knpu_oauth2_client.yaml
            ->getClient('facebook_main');
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // on success, let the request continue
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $message = strtr($exception->getMessageKey(), $exception->getMessageData());

        return new Response($message, 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)
    {
        return new RedirectResponse(
            '/connect/', // might be the site, where users choose their oauth provider
            Response::HTTP_TEMPORARY_REDIRECT
        );
    }


}

我的用户是在我的数据库中创建的,具有正确的数据,但无法对其进行身份验证。

感谢您帮助我,如果您想要 FacebookController.php 的代码,请告诉我,然后我将编辑我的帖子。

编辑:

在此处输入图像描述

编辑 2:

public function getUser($credentials, UserProviderInterface $userProvider)
    {
        /** @var FacebookUser $facebookUser */

        $client = $this->clientRegistry->getClient('facebook_main');
        $accessToken = $client->getAccessToken();
        if ($accessToken && !$accessToken->getToken()) {
            dump("User is not found!"); die;
        }
        $provider = $client->getOAuth2Provider();
        $longLivedToken = $provider->getLongLivedAccessToken($accessToken);
        //I get the user by using long lived token
        $facebookUser = $client->fetchUserFromToken($longLivedToken);

        $email = $facebookUser->getEmail();

        // 1) have they logged in with Facebook before? Easy!
        $existingUser = $this->em->getRepository(User::class)
            ->findOneBy(['facebookId' => $facebookUser->getId()]);
        if ($existingUser) {
            return $existingUser;
        }

        // 2) do we have a matching user by email?
        $user = $this->em->getRepository(User::class)
            ->findOneBy(['email' => $email]);

        // 3) Maybe you just want to "register" them by creating
        // a User object
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";

        if(!$user) {
            $user = new User();
            $user->setFacebookId($facebookUser->getId());
            $user->setUsername($facebookUser->getEmail());
            $user->setPassword(password_hash(substr(str_shuffle($chars), 0, 10), PASSWORD_DEFAULT));
            $user->setPrenom($facebookUser->getFirstName());
            $user->setNom($facebookUser->getLastName());
            $user->setEmail($facebookUser->getEmail());
            $user->setEnabled(true);
            $user->setSocialAuthentication(true);
        }
        $this->em->persist($user);
        $this->em->flush();


        return $user;
    }

我有同样的问题,我已经用这种方式引用了 long live access token。 这可能是一个解决方案。 这个给你。

$client = $clientRegistry->getClient('facebook_main');
$accessToken = $client->getAccessToken();
if ($accessToken && !$accessToken->getToken()) {
    dump("User is not found!"); die;
}
$provider = $client->getOAuth2Provider();
$longLivedToken = $provider->getLongLivedAccessToken($accessToken);
//I get the user by using long lived token
$facebookUser = $client->fetchUserFromToken($longLivedToken);

您遇到的第一个错误:

获取 OAuth 凭据时出错:“OAuthException:已使用此授权码。”。

那是因为您重新加载了您的页面(例如,在更改代码和刷新之后)。 错误消息说之前使用过 Url Params 中的授权码。 而是刷新您的站点 1. 返回放置按钮的站点,然后 2. 通过单击 FB 登录按钮获取新的授权代码。

现在这个错误消失了,您可以继续调试您的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM