phpauthenticationsymfonyoauth-2.0twitter-oauth

Error fetching OAuth credentials: "Missing required parameter [code_verifier]."


I'm encountering an issue with my OAuth implementation, specifically when trying to fetch credentials. The error message I'm receiving is:

Error fetching OAuth credentials: "Missing required parameter [code_verifier]."

I'm using Symfony with the knpu/oauth2-client bundle to integrate with an OAuth 2.0 provider (e.g., Twitter). The specific provider class I'm using is \Smolblog\OAuth2\Client\Provider\Twitter.

Here are relevant portions of my Symfony configuration (knpu_oauth2_client.yaml), especially related to the Twitter provider:

knpu_oauth.yaml :

```type: generic
provider_class: '\Smolblog\OAuth2\Client\Provider\Twitter'
client_id: '%env(resolve:TWITTER_CLIENT_ID)%'
client_secret: '%env(resolve:TWITTER_CLIENT_SECRET)%'
redirect_route: connect_twitter_check
redirect_params: {}
# Other relevant configurations```
public function redirectToTwitter(ClientRegistry $clientRegistry)
{
    return $clientRegistry
        ->getClient('twitter')
        ->redirect(['users.read'], ['code_challenge']); // Scopes you need
}

#[Route(path: '/Connexion/twitter/check', name: 'connect_twitter_check')]
public function connectTwitter(Request $request, ClientRegistry $clientRegistry)
{} 

authenticate method :

 {
     $client = $this->clientRegistry->getClient('twitter');
     //dd($client);
     $accessToken = $this->fetchAccessToken($client);
     // dd($client);
     return new SelfValidatingPassport(
         new UserBadge($accessToken->getToken(), function () use ($accessToken, $client) {
             /** @var TwitterUser $twitterUser */
             $twitterUser = $client->fetchUserFromToken($accessToken);
             dd($twitterUser);
             $email = $twitterUser->getEmail();
             // dd($email);
             // dd($accessToken);
             // 1) have they logged in with Twitter before? Easy!
             $existingUser = $this->entityManager->getRepository(User::class)->findOneBy(['twitterId' => $twitterUser->getId()]);
             // dd($existingUser);
             if ($existingUser) {
                 return $existingUser;
             } else {
                 // 2) do we have a matching user by email?
                 $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
                 // dd($user);
                 if (!$user) {
                     /** @var Particulier $user */
                     $user = new Particulier();
                     $user->setEmail($email);
                     $user->setPassword($this->encoder->hashPassword($user, '@user0123456'));
                     $user->setTypeCompte("Particulier");
                     $user->setTel("+221765897845");
                     $user->setPrenom("nom");
                     $user->setNom("nom");
                     $user->setcivility("Mr");
                 }

I have this error after clicking the authorization button:

Questions:

  1. How can I ensure that the required parameter [code_verifier] is properly included in the OAuth request?
  2. Are there specific configurations in the Twitter Developer App that I should check to address this issue?
  3. Is there a known issue or workaround related to the "Missing required parameter [code_verifier]" error in the knpu/oauth2-client bundle?

Solution

  • Finally, I have figured out after updating :

    #[Route(path: '/Connexion/twitter', name: 'app_twitter_start')]
        public function redirectToTwitter(ClientRegistry $clientRegistry, Request $request)
        {
            $session = $request->getSession();
            $codeVerifier = bin2hex(random_bytes(64));
    
            // URL-encode the code verifier
            $urlEncodedCodeVerifier = urlencode($codeVerifier);
    
            // Use SHA-256 to hash the URL-encoded code verifier
            $codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $urlEncodedCodeVerifier, true)), '+/', '-_'), '=');
    
            // Log or print the values for debugging
            echo "Code Verifier: $codeVerifier\n";
            echo "Code Challenge: $codeChallenge\n";
    
            // Store the code verifier in the session
            $session->set('oauth2verifier', $codeVerifier);
    
    
            $authUrl = $clientRegistry
                ->getClient("twitter")
                ->redirect(["users.read","offline.access","tweet.read"], ["code_challenge" => $codeChallenge,"code_challenge_method" => "S256"]);
            // dd($authUrl);
            return $authUrl;
        }
    

    and this in the authenticate method :

    $client = $this->clientRegistry->getClient('twitter');
    
            $session = $request->getSession();
             // Get the code verifier from the session
             $codeVerifier = $session->get('oauth2verifier');
             // echo "Code Verifier for Access Token Request: $codeVerifier\n";
             $authorizationCode = $request->query->get('code');
            // rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
             // dd($authorizationCode);
            // dd($codeVerifier);
    
             $provider = $client->getOAuth2Provider();
             $accessToken = $provider->getAccessToken('authorization_code', [
                        'code' => $authorizationCode,
                        'code_verifier' => $codeVerifier,
                     ]);
     return new SelfValidatingPassport(
                new UserBadge($accessToken->getToken(), function () use ($accessToken, $client) {
    
                    /** @var TwitterUser $twitterUser */
                    $twitterUser = $client->fetchUserFromToken($accessToken);
     .........}
    

    I forgot include the default scopes offline.access and tweet.read