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.
Installation
Add the bundle to AppKernel.php:
new AdrienBrault\OAuth2FacebookGrantBundle\ABOAuth2FacebookGrantBundle(),
Require the package via Composer:
composer require adrienbrault/oauth2-facebook-grant-bundle
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
First Use Case
{
"grant_type": "facebook",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"facebook_access_token": "USER_FACEBOOK_TOKEN"
}
fb_id, and returns an OAuth2 access token for your API.Facebook SSO Flow
User Provider Pattern
UserProviderInterface to map Facebook IDs to your app’s users:
class FacebookUserProvider implements UserProviderInterface {
public function loadUserByUsername($facebookId) {
return $userRepository->findOneBy(['facebook_id' => $facebookId]);
}
}
UserManager or EntityManager to handle user creation/updates.Token Validation
FacebookGrant class (see Gotchas).API Security
FOSOAuthServerBundle).fos_oauth_server_token:
path: /connect/token
defaults: { _controller: FOSOAuthServerBundle:Token:checkToken }
User Association
if (!$user) {
$user = $this->userManager->createUser([
'facebook_id' => $facebookId,
'email' => $facebookData['email'], // From Facebook API
'username' => 'fb_' . $facebookId,
]);
}
Facebook Token Expiry
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.
}
Missing fb_id in Response
curl -G "https://graph.facebook.com/me?access_token=USER_TOKEN"
FacebookGrant class (extend it to log raw Facebook API responses).CORS Issues
// In your security config
$this->addCorsMapping([
'path' => '^/connect/token',
'allowed_origins' => ['https://your-frontend.com'],
]);
Bundle Version Mismatch
FOSOAuthServerBundle is installed. Ensure compatibility:
composer require friendsofsymfony/oauth-server-bundle:^1.0
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 }
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.
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
}
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);
Performance
EventDispatcher to trigger post-login events (e.g., analytics).How can I help you explore Laravel packages today?