Installation
composer require ailove-dev/facebook-bundle
Ensure ailove-dev/abstract-social-bundle and friendsofsymfony/facebook-bundle are also installed (handled via dependency).
Enable the Bundle
Add to config/bundles.php:
Ailove\FacebookBundle\AiloveFacebookBundle::class => ['all' => true],
Configure Facebook App
Update .env with your Facebook App credentials:
FACEBOOK_APP_ID=your_app_id
FACEBOOK_APP_SECRET=your_app_secret
FACEBOOK_REDIRECT_URI=http://your-app.dev/connect/facebook/check
Extend FOSUserBundle
Override User entity to include Facebook-specific fields (e.g., facebookId):
// src/Entity/User.php
use Ailove\AbstractSocialBundle\Model\SocialUserInterface;
class User extends BaseUser implements SocialUserInterface
{
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $facebookId;
}
First Use Case: Login Flow
Add a route to trigger Facebook auth (e.g., login/facebook):
# config/routes.yaml
facebook_login:
path: /login/facebook
controller: AiloveFacebookBundle:Security:login
Redirect users to /login/facebook to start the OAuth flow.
Trigger OAuth Flow Use the bundle’s controller to redirect to Facebook:
// src/Controller/AuthController.php
use Ailove\FacebookBundle\Controller\SecurityController;
class AuthController extends SecurityController
{
public function loginAction()
{
return $this->get('facebook.security.authentication.manager')->authenticate();
}
}
Handle Callback
The bundle auto-handles the callback at /connect/facebook/check. Customize behavior by overriding the AuthenticationSuccessHandler:
# config/services.yaml
services:
App\Security\FacebookAuthSuccessHandler:
class: App\Security\FacebookAuthSuccessHandler
arguments: ['@router', '@fos_user.user_manager']
tags:
- { name: 'monolog.logger', channel: 'security' }
Post-Auth Logic
Extend UserProvider to link Facebook accounts to existing users or create new ones:
// src/Security/FacebookUserProvider.php
use Ailove\AbstractSocialBundle\Provider\SocialUserProvider;
class FacebookUserProvider extends SocialUserProvider
{
protected function getSocialId($data)
{
return $data['id']; // Facebook user ID
}
protected function getSocialUsername($data)
{
return $data['email'] ?? $data['id'] . '@facebook.com';
}
}
User Entity Mapping
Ensure your User entity implements SocialUserInterface and maps Facebook fields:
public function setFacebookId(?string $facebookId): self
{
$this->facebookId = $facebookId;
return $this;
}
public function getFacebookId(): ?string
{
return $this->facebookId;
}
UserManager) for post-auth user handling.getSocialExtraData() in your UserProvider to fetch additional Facebook profile fields (e.g., name, picture):
protected function getSocialExtraData($data)
{
return [
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'picture' => 'https://graph.facebook.com/' . $data['id'] . '/picture?type=large',
];
}
$facebookService = $this->createMock(\Facebook\FacebookSession::class);
$facebookService->method('getToken')->willReturn('test_token');
$this->container->set('facebook.session', $facebookService);
Deprecated Dependencies
friendsofsymfony/facebook-bundle (v1.x), which is outdated. Expect compatibility issues with newer Symfony/FOSUserBundle versions.Missing Documentation
Ailove\AbstractSocialBundle for patterns, then extend FacebookBundle classes (e.g., AuthenticationManager).CSRF Token Mismatch
config/packages/security.yaml:
firewalls:
main:
form_login:
check_path: /login_check
facebook_login:
pattern: ^/login/facebook
csrf_token_generator: security.csrf.token_manager
User Linking Logic
loadUserBySocialId() to merge accounts:
public function loadUserBySocialId($socialId)
{
$user = $this->findUserBy(['facebookId' => $socialId]);
if (!$user) {
$user = $this->createUserFromSocialData($socialData);
}
return $user;
}
facebook/facebook-php-sdk-v4 for debugging:
$fb = \Facebook\Facebook::newInstance([...]);
try {
$response = $fb->get('/me?fields=id,name,email');
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// Handle invalid response
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// Handle SDK errors
}
getSocialExtraData() to inspect raw Facebook responses.Custom Authentication Manager
Override AiloveFacebookBundle\Security\Authentication\AuthenticationManager to add pre/post-auth logic:
class CustomAuthManager extends AuthenticationManager
{
protected function createAuthenticatedToken($user, $providerKey)
{
// Add custom claims or metadata
$token = parent::createAuthenticatedToken($user, $providerKey);
$token->setAttribute('facebook_data', $this->getSocialExtraData($this->getSessionData()));
return $token;
}
}
Dynamic Redirects
Extend AuthenticationSuccessHandler to redirect based on user roles:
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
if ($user->hasRole('ROLE_ADMIN')) {
return new RedirectResponse('/admin');
}
return new RedirectResponse('/dashboard');
}
Rate Limiting
Add a decorator to facebook.session to handle Facebook API rate limits:
$session = $this->get('facebook.session');
if ($session instanceof \Facebook\FacebookSession) {
$session->setDefaultApplication($this->getFacebookApp());
$session->setDefaultAccessToken($this->getAccessToken());
}
How can I help you explore Laravel packages today?