Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Oauth2 Facebook Grant Bundle Laravel Package

adrienbrault/oauth2-facebook-grant-bundle

Symfony bundle that adds a Facebook access-token grant to FOSOAuthServerBundle. Lets your API exchange a valid Facebook token for an OAuth2 access token, resolving the user via a custom Facebook user provider for mobile/SSO logins.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle to AppKernel.php:

    new AdrienBrault\OAuth2FacebookGrantBundle\ABOAuth2FacebookGrantBundle(),
    

    Require the package via Composer:

    composer require adrienbrault/oauth2-facebook-grant-bundle
    
  2. Configuration Add the bundle configuration to config.yml:

    ab_oauth2_facebook_grant:
        user_provider: your_bundle.facebook_user_provider
        uri: "http://your-api.com/connect/token"  # OAuth2 token endpoint
    
  3. First Use Case

    • Frontend (Mobile/Web): Collect a valid Facebook access token from the user.
    • API Request: Send a POST request to your OAuth2 token endpoint with:
      {
        "grant_type": "facebook",
        "client_id": "your_client_id",
        "client_secret": "your_client_secret",
        "facebook_access_token": "USER_FACEBOOK_TOKEN"
      }
      
    • Backend: The bundle validates the Facebook token, fetches the fb_id, and returns an OAuth2 access token for your API.

Implementation Patterns

Workflow Integration

  1. Facebook SSO Flow

    • Use the bundle to offload Facebook authentication to your API.
    • Example: iOS/Android apps can skip native Facebook SDK and use a webview or direct API call.
  2. User Provider Pattern

    • Implement UserProviderInterface to map Facebook IDs to your app’s users:
      class FacebookUserProvider implements UserProviderInterface {
          public function loadUserByUsername($facebookId) {
              return $userRepository->findOneBy(['facebook_id' => $facebookId]);
          }
      }
      
    • Use UserManager or EntityManager to handle user creation/updates.
  3. Token Validation

    • The bundle automatically validates the Facebook token via Facebook’s API.
    • Customize validation by extending the bundle’s FacebookGrant class (see Gotchas).
  4. API Security

    • Protect the token endpoint with OAuth2 server middleware (e.g., FOSOAuthServerBundle).
    • Example route:
      fos_oauth_server_token:
          path: /connect/token
          defaults: { _controller: FOSOAuthServerBundle:Token:checkToken }
      
  5. User Association

    • Link Facebook accounts to existing users or create new ones:
      if (!$user) {
          $user = $this->userManager->createUser([
              'facebook_id' => $facebookId,
              'email' => $facebookData['email'], // From Facebook API
              'username' => 'fb_' . $facebookId,
          ]);
      }
      

Gotchas and Tips

Pitfalls

  1. Facebook Token Expiry

    • Facebook access tokens expire (typically 1–2 hours). Handle OAuthServerException for invalid tokens:
      try {
          $accessToken = $this->get('fos_oauth_server.server')->checkToken($grant);
      } catch (\RuntimeException $e) {
          // Token expired; redirect user to re-authenticate via Facebook.
      }
      
  2. Missing fb_id in Response

    • Ensure the Facebook token is a user access token (not an app token). Test with:
      curl -G "https://graph.facebook.com/me?access_token=USER_TOKEN"
      
    • Debug by inspecting the bundle’s FacebookGrant class (extend it to log raw Facebook API responses).
  3. CORS Issues

    • If your frontend is on a different domain, configure CORS on your API’s token endpoint:
      // In your security config
      $this->addCorsMapping([
          'path' => '^/connect/token',
          'allowed_origins' => ['https://your-frontend.com'],
      ]);
      
  4. Bundle Version Mismatch

    • The bundle assumes FOSOAuthServerBundle is installed. Ensure compatibility:
      composer require friendsofsymfony/oauth-server-bundle:^1.0
      

Tips

  1. Extend FacebookGrant for Custom Logic Override the validateFacebookToken() method to add custom checks:

    use AdrienBrault\OAuth2FacebookGrantBundle\Grant\FacebookGrant as BaseFacebookGrant;
    
    class CustomFacebookGrant extends BaseFacebookGrant {
        protected function validateFacebookToken($accessToken) {
            $response = $this->httpClient->get('https://graph.facebook.com/me?access_token=' . $accessToken);
            $data = json_decode($response->getBody(), true);
    
            if (empty($data['id'])) {
                throw new \RuntimeException('Invalid Facebook token');
            }
            return $data['id'];
        }
    }
    

    Register the custom grant in services.yml:

    services:
        custom.facebook.grant:
            class: Your\Bundle\Grant\CustomFacebookGrant
            tags:
                - { name: fos_oauth_server.grant }
    
  2. Debugging Facebook API Calls Enable debug mode in the bundle’s FacebookGrant:

    $this->httpClient->setDebug(true); // Add to validateFacebookToken()
    

    Check logs for raw responses from Facebook’s /me endpoint.

  3. User Provider Caching Cache user lookups in loadUserByUsername() to reduce database calls:

    public function loadUserByUsername($facebookId) {
        return $this->userManager->getRepository()
            ->findOneBy(['facebook_id' => $facebookId])
            ->orCreateFromFacebook($facebookId); // Custom method
    }
    
  4. Testing Use the Facebook Graph API Explorer to generate test tokens. Mock the HTTP client in tests:

    $client = $this->createMock(GuzzleHttpClient::class);
    $client->method('get')->willReturn(new StreamResponse(fopen('data:test/json', 'r')));
    $grant = new FacebookGrant($client, $userProvider);
    
  5. Performance

    • Batch user creation/updates if handling many Facebook logins.
    • Use Symfony’s EventDispatcher to trigger post-login events (e.g., analytics).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver