An opinionated way to authenticate users using Laravel Socialite.
Contents
·
Installation
·
Usage
Bartender serves you a controller, routes, and a default implementation for easily handling authentication with Laravel Socialite providers. Almost everything in Bartender can be customized.
Contents
Requirements
- PHP >= 8.0
- Laravel >= 9.0
- Laravel Socialite >= 5.0
Installation
You can install the package via composer:
composer require directorytree/bartender
Then, publish the migrations. They will create the required columns on the users table:
provider_id
provider_name
provider_access_token
provider_refresh_token
If your application does not need to store/access provider tokens, you may delete the 2024_10_27_131354_add_provider_token_columns_to_users_table.php migration.
php artisan vendor:publish --provider="DirectoryTree\Bartender\BartenderServiceProvider"
Finally, run the migrations:
Setup
Register the authentication routes using Bartender::routes().
This will register the /auth/{driver}/redirect and /auth/{driver}/callback routes.
// routes/web.php
use DirectoryTree\Bartender\Facades\Bartender;
Bartender::routes();
Set up any Socialite Providers you need, and update your services.php configuration file with the redirect URL for each provider:
Important
Remember to fully complete the installation steps for each Socialite Provider you wish to use.
If you receive a Driver [X] not supported exception, you have not completed the installation steps for the provider.
// config/services.php
return [
// ...
'google' => [
// ...
'redirect' => '/auth/google/callback',
],
'microsoft' => [
// ...
'redirect' => '/auth/microsoft/callback',
],
];
Finally, register the Socialite Provider in your AppServiceProvider using Bartender::serve():
// app/Providers/AppServiceProvider.php
use DirectoryTree\Bartender\Facades\Bartender;
class AppServiceProvider extends ServiceProvider
{
// ...
public function boot(): void
{
Bartender::serve('google');
Bartender::serve('microsoft');
}
}
If your application uses a User model outside the default App\Models namespace, you can set it using the Bartender facade.
If your application uses the default Laravel User model in the App\Models namespace, skip this step.
// app/Providers/AuthServiceProvider.php
use App\User;
use DirectoryTree\Bartender\Facades\Bartender;
class AuthServiceProvider extends ServiceProvider
{
// ...
public function boot(): void
{
Bartender::setUserModel(User::class);
}
}
Usage
Direct your user to the /auth/{driver}/redirect route to authenticate with the given driver:
<a href="{{ route('auth.driver.redirect', 'google') }}">
Login with Google
</a>
<a href="{{ route('auth.driver.redirect', 'microsoft') }}">
Login with Microsoft
</a>
Once the user successfully authenticates, they will be redirected to the /auth/{driver}/callback
route, which will automatically create or update their application user account.
Important
If you receive a Routing requirement for "driver" cannot be empty exception upon clicking
one of the login links, you have forgotten to register your the Socialite provider with
Bartender using Bartender::serve() in your AppServiceProvider.
Provider Identity
Returning users are matched by provider name and provider ID. Their email address and
profile information are updated when the provider reports a change. An email address
already belonging to another identity is rejected; Bartender does not automatically
link accounts by email.
Missing provider IDs throw an AuthenticationException and are handled as authentication
failures rather than email conflicts. Provider names and IDs are compared exactly before
an existing account is updated, even when the database uses case-insensitive comparisons.
Case-only conflicts are rejected; applications that need to store both identities must
configure case-sensitive provider columns and uniqueness constraints themselves.
Soft Deletes
With the default UserProviderRepository, soft-deleted users will be restored if they log in with their provider.
To prevent provider sign-in from restoring or recreating a soft-deleted account, disable
restoration in your service provider:
Bartender::dontRestoreSoftDeletedUsers();
Automatic restoration remains enabled by default. To explicitly allow restoration again,
call Bartender::dontRestoreSoftDeletedUsers(false). You can inspect the current policy
with Bartender::shouldRestoreSoftDeletedUsers().
When restoration is disabled, Bartender rejects
a deleted account by its provider identity or email address, including when the
provider reports a different email. Rejected deleted accounts raise an
AuthenticationException rather than being reported as email conflicts. The account
is checked again before updating, and its deletion timestamp is only cleared when
restoration is enabled. You can also swap out the repository
for a custom policy.
Email Verification
With the default UserProviderRepository, users with emails will be automatically verified (by setting the email_verified_at timestamp column) if it is not already set.
To change this behaviour, swap out the repository.
Access/Refresh Tokens
To enable storing the authentication provider access and refresh tokens
on your user so that you can access them later, you may apply the
StoresProviderTokens interface on your model:
// app/Models/User.php
namespace App\Models;
use DirectoryTree\Bartender\StoresProviderTokens;
class User extends Authenticatable implements StoresProviderTokens
{
// ...
}
You may also want to add these columns to your model's $hidden attributes, along with encrypted casts for additional security:
// app/Models/User.php
class User extends Authenticatable implements StoresProviderTokens
{
/**
* The attributes that should be hidden for serialization.
*/
protected $hidden = [
'provider_access_token',
'provider_refresh_token'
];
/**
* Get the attributes that should be cast.
*/
protected function casts(): array
{
return [
'provider_access_token' => 'encrypted',
'provider_refresh_token' => 'encrypted',
];
}
}
Otherwise, if you do not need to store these tokens, you are free to delete the
published 2024_10_27_131354_add_provider_token_columns_to_users_table.php
migration file and omit applying the StoresProviderTokens interface.
Bartender will skip storing these tokens as it does not
require them to successfully authenticate users.
Extending & Customizing
Almost everything can be swapped out in Bartender.
If you would like to handle everything yourself for OAuth redirects and callbacks, you may create your own ProviderHandler:
// app/Socialite/UserProviderHandler.php
namespace App\Socialite;
use Illuminate\Http\Request;
use Laravel\Socialite\Contracts\Provider;
use DirectoryTree\Bartender\ProviderHandler;
class UserProviderHandler implements ProviderHandler
{
/**
* Constructor.
*/
public function __construct(
protected Request $request
) {
}
/**
* Handle redirecting the user to the OAuth provider.
*/
public function redirect(Provider $provider, string $driver): RedirectResponse
{
// Perform additional logic here...
return $provider->redirect();
}
/**
* Handle an OAuth response from the provider.
*/
public function callback(Provider $provider, string $driver): RedirectResponse
{
// Authenticate the user your own way...
return redirect()->route('dashboard');
}
}
Then, provide it into the second argument in the Bartender::serve method:
// app/Providers/AuthServiceProvider.php
namespace App\Providers;
use App\Socialite\UserProviderHandler;
use DirectoryTree\Bartender\Facades\Bartender;
class AuthServiceProvider extends ServiceProvider
{
// ...
public function boot(): void
{
Bartender::serve('google', UserProviderHandler::class);
Bartender::serve('microsoft', UserProviderHandler::class);
}
}
You may also extend the built-in UserProviderHandler implementation if you prefer.
For example, if you need to adjust the scopes for a single provider:
// app/Socialite/MicrosoftUserHandler.php
namespace App\Socialite;
use Illuminate\Http\RedirectResponse;
use Laravel\Socialite\Contracts\Provider;
use DirectoryTree\Bartender\UserProviderHandler;
class MicrosoftUserHandler extends UserProviderHandler
{
/**
* Handle redirecting the user to Microsoft.
*/
public function redirect(Provider $provider, string $driver): RedirectResponse
{
$provider->scopes([
'Mail.ReadWrite',
// ...
]);
return parent::redirect($provider, $driver);
}
}
Then register it as the handler:
Bartender::serve('microsoft', MicrosoftUserHandler::class);
User Creation & Updating
If you would like to customize the creation of the user in the default
handler, you may create your own ProviderRepository implementation: