derrabus/twitter-signin-bundle
Installation
composer require derrabus/twitter-signin-bundle
Add to config/app.php under providers:
Derrabus\TwitterSigninBundle\TwitterSigninServiceProvider::class,
Publish config (optional but recommended):
php artisan vendor:publish --provider="Derrabus\TwitterSigninBundle\TwitterSigninServiceProvider"
Environment Configuration
Add Twitter API credentials to .env:
TWITTER_SIGNIN_CLIENT_ID=your_client_id
TWITTER_SIGNIN_CLIENT_SECRET=your_client_secret
TWITTER_SIGNIN_CALLBACK_URL=/auth/twitter/callback
First Use Case: OAuth Flow
routes/web.php:
Route::get('/auth/twitter', [TwitterAuthController::class, 'redirectToTwitter'])->name('twitter.login');
Route::get('/auth/twitter/callback', [TwitterAuthController::class, 'handleTwitterCallback']);
<a href="{{ route('twitter.login') }}">Sign in with Twitter</a>
Redirect to Twitter Use the controller method to initiate OAuth:
$authUrl = TwitterAuthController::redirectToTwitter();
return redirect()->to($authUrl);
Handle Callback Process the OAuth response:
public function handleTwitterCallback()
{
$user = TwitterAuthController::handleTwitterCallback(request());
// Store user data in session or create a Laravel user
auth()->login($user);
return redirect()->intended('/dashboard');
}
User Data Handling
Extend the TwitterUser model or use a service to map Twitter data to your user model:
$twitterUser = TwitterAuthController::getTwitterUser($accessToken);
$localUser = User::firstOrCreate([
'email' => $twitterUser->email,
], [
'name' => $twitterUser->name,
'twitter_id' => $twitterUser->id,
]);
Laravel Auth Integration
Use Laravel’s built-in Authenticatable traits to handle sessions:
auth()->login($localUser);
Custom User Mapping
Override the TwitterAuthController to customize user creation:
class CustomTwitterAuthController extends TwitterAuthController
{
protected function createUserFromTwitter(array $twitterData)
{
return User::create([
'name' => $twitterData['name'],
'email' => $twitterData['email'] ?? $twitterData['id'] . '@twitter.com',
'avatar' => $twitterData['profile_image_url_https'],
]);
}
}
Scopes and Permissions Request additional permissions in the config:
TWITTER_SIGNIN_SCOPES="users.read follow_readwrite"
Callback URL Mismatch
Ensure TWITTER_SIGNIN_CALLBACK_URL matches the route exactly (including trailing slashes). Twitter’s OAuth validation is strict.
State Parameter
The package does not handle CSRF protection via state by default. Manually add it to the redirect URL:
$state = Str::random(40);
session(['twitter_oauth_state' => $state]);
$authUrl = TwitterAuthController::redirectToTwitter(['state' => $state]);
Token Expiry Access tokens expire. Implement token refresh logic or use short-lived tokens with server-side storage.
Rate Limits Twitter’s API has rate limits. Cache user data to avoid repeated calls:
$user = Cache::remember("twitter_user_{$twitterId}", now()->addHours(1), function() use ($accessToken) {
return TwitterAuthController::getTwitterUser($accessToken);
});
Enable Logging
Add to config/twitter-signin.php:
'debug' => env('APP_DEBUG', false),
Check storage/logs/laravel.log for OAuth errors.
Test with Postman Manually test the OAuth flow using Postman to isolate issues:
GET https://api.twitter.com/oauth2/token
Headers: Authorization: Basic {base64(client_id:client_secret)}
Body: grant_type=authorization_code&code={callback_code}&redirect_uri={callback_url}
Custom User Provider
Implement Derrabus\TwitterSigninBundle\Contracts\UserProvider to override user creation:
class CustomUserProvider implements UserProvider
{
public function createUser(array $twitterData)
{
// Custom logic
}
}
Register in config/twitter-signin.php:
'user_provider' => \App\Services\CustomUserProvider::class,
Webhook Handling Extend for real-time updates (e.g., profile changes):
Event::listen(TwitterUserUpdated::class, function ($event) {
// Sync local user data
});
Multi-Tenant Support Store Twitter user data in a pivot table for tenant isolation:
$user->twitterAccounts()->create([
'provider_id' => $twitterUser->id,
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
]);
How can I help you explore Laravel packages today?